示例#1
0
        public XnaContentProject(Task task, string msBuildPath, string xnaInstallPath)
        {
            m_engine = new Engine(msBuildPath);
            m_engine.RegisterLogger(new XnaContentLogger(task));
            m_project = new Project(m_engine);

            m_project.AddNewUsingTaskFromAssemblyName("BuildContent", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d");
            m_project.AddNewUsingTaskFromAssemblyName("BuildXact", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d");

            // Add our Content Pipeline Assemblies
            m_pipelineGroup = m_project.AddNewItemGroup();
            m_contentGroup  = m_project.AddNewItemGroup();

            m_contentTarget = m_project.Targets.AddNewTarget("_BuildXNAContentLists");

            // Add our Build target
            m_xnaTarget = m_project.Targets.AddNewTarget("Build");
            m_xnaTarget.DependsOnTargets = "_BuildXNAContentLists";

            // Add Default Pipeline Assemblies.
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll");
        }
示例#2
0
        public XnaContentProject(Task task, string msBuildPath, string xnaInstallPath)
        {
            m_engine = new Engine(msBuildPath);
            m_engine.RegisterLogger(new XnaContentLogger(task));
            m_project = new Project(m_engine);

            m_project.AddNewUsingTaskFromAssemblyName("BuildContent", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d");
            m_project.AddNewUsingTaskFromAssemblyName("BuildXact", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d");

            // Add our Content Pipeline Assemblies
            m_pipelineGroup = m_project.AddNewItemGroup();
            m_contentGroup = m_project.AddNewItemGroup();

            m_contentTarget = m_project.Targets.AddNewTarget("_BuildXNAContentLists");

            // Add our Build target
            m_xnaTarget = m_project.Targets.AddNewTarget("Build");
            m_xnaTarget.DependsOnTargets = "_BuildXNAContentLists";

            // Add Default Pipeline Assemblies.
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll");
            AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll");
        }
        public override bool Execute()
        {
            bool result = true;

            string file = Path.Combine(m_stubsPath, m_name + ".featureproj");

            try
            {
                Project proj = new Project();
                proj.DefaultToolsVersion = "3.5";
                proj.DefaultTargets = "Build";

                BuildPropertyGroup bpg = proj.AddNewPropertyGroup(true);
                bpg.AddNewProperty("FeatureName", m_name);
                bpg.AddNewProperty("Guid", System.Guid.NewGuid().ToString("B"));
                bpg.AddNewProperty("Description", "");
                bpg.AddNewProperty("Groups", "");

                BuildItemGroup big = proj.AddNewItemGroup();
                big.AddNewItem("InteropFeature", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_'));
                big.AddNewItem("DriverLibs", Path.GetFileNameWithoutExtension( m_assemblyName ).Replace( '.', '_' ) + ".$(LIB_EXT)");
                big.AddNewItem("MMP_DAT_CreateDatabase", "$(BUILD_TREE_CLIENT)\\pe\\" + m_assemblyName);
                big.AddNewItem("RequiredProjects", Path.Combine(m_stubsPath, m_nativeProjectFile));

                proj.Save(file);
            }
            catch(Exception e)
            {
                Log.LogError("Error trying to create feature project file \"" + file + "\": " + e.Message);
                result = false;
            }

            return result;
        }
        private void BuildProject(IEnumerable <BuildItemFileInfo> buildItemFiles, Engine engine)
        {
            Microsoft.Build.BuildEngine.Project proj = engine.CreateNewProject();

            engine.RegisterLogger(new Log4NetMSBuildLogger(engine, proj));
            engine.RegisterLogger(new BuildLogMSBuildLogger(engine, proj));
            AssemblyName      = Path.GetFileNameWithoutExtension(c_AssemblyName);
            proj.FullFileName = Path.Combine(LibraryPath, String.Format("{0}.csproj", AssemblyName));
            ConfigureProject(proj);

            BuildItemGroup items = proj.AddNewItemGroup();

            foreach (BuildItemFileInfo buildItemFile in buildItemFiles)
            {
                AddFileToProject(items, buildItemFile.Path, buildItemFile.Generator.MSBuildItemType);

                if (buildItemFile.Generator.DeployFile)
                {
                    AddOutputFile(buildItemFile.Path);
                }
            }

            proj.Save(Path.Combine(FullProjectDirectory, AssemblyName + ".csproj"));

            if (!engine.BuildProject(proj))
            {
                throw new BuildException(String.Format(CultureInfo.CurrentUICulture, "Failed to build {0}", c_AssemblyName));
            }

            string asmFileName = Path.Combine(OutputPath, c_AssemblyName);

            AddOutputFile(asmFileName);

            // deploy the associated .pdb, if it exists.
            string pdbFileName = Path.ChangeExtension(asmFileName, ".pdb");

            if (File.Exists(pdbFileName))
            {
                AddOutputFile(pdbFileName);
            }
        }
示例#5
0
        private void OnResetCsproj()
        {
            String sourceRoot = ConfigurationManager.AppSettings["source_root"];
            String csprojName = ConfigurationManager.AppSettings["csproj_name"];

            String csprojFile = sourceRoot + csprojName;

            Project project = new Project();
            project.Load(csprojFile);

            BuildItemGroup itemGroup = project.AddNewItemGroup();

            itemGroup.AddNewItem("Content", "_static\\data\\okr.me");
            itemGroup.AddNewItem("Content", "_static\\data\\cover.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-bg.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-icon.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okr-splash.png");
            itemGroup.AddNewItem("Content", "_static\\data\\okrapp.config");

            String[] appFiles = Directory.GetFileSystemEntries(sourceRoot + "_static\\data\\app\\");

            foreach (var file in appFiles)
            {
                itemGroup.AddNewItem("Content", "_static\\data\\app\\" + Path.GetFileName(file));
            }

            String[] bookFiles = Directory.GetFileSystemEntries(sourceRoot + "_static\\data\\book\\");

            foreach (var file in bookFiles)
            {
                itemGroup.AddNewItem("Content", "_static\\data\\book\\" + Path.GetFileName(file));
            }

            project.Save(csprojFile);
        }
示例#6
0
        private void OnCleanUp()
        {
            String sourceRoot = ConfigurationManager.AppSettings["source_root"];
            String csprojName = ConfigurationManager.AppSettings["csproj_name"];

            String csprojFile = sourceRoot + csprojName;

            Project project = new Project();
            project.Load(csprojFile);

            project.RemoveItemsByName("Content");

            // 补上img文件夹
            BuildItemGroup itemGroup = project.AddNewItemGroup();
            String[] bookFiles = Directory.GetFileSystemEntries(sourceRoot + "_static\\img\\");

            foreach (var file in bookFiles)
            {
                itemGroup.AddNewItem("Content", "_static\\img\\" + Path.GetFileName(file));
            }

            project.Save(csprojFile);
        }
        protected override void OnClosed(EventArgs e)
        {
            if (_savedChanges)
            {
                // Make sure the current document has the necessary
                // extensions loaded.
                // UNDONE: We should be able to do this with the document
                // closed or open as text as well via a registered service
                // on the ORMDesignerPackage, but this is sufficient for now.
                Dictionary <string, string> requiredExtensions = null;
                string[] loadedExtensions = null;
                foreach (IORMGenerator selectedGenerator in _mainBranch.SelectedGenerators)
                {
                    foreach (string requiredExtension in selectedGenerator.GetRequiredExtensionsForInputFormat("ORM"))
                    {
                        if (loadedExtensions == null)
                        {
                            loadedExtensions = (new ORMExtensionManager(_projectItem)).GetLoadedExtensions(_serviceProvider);
                        }
                        if (Array.BinarySearch <string>(loadedExtensions, requiredExtension) < 0)
                        {
                            if (requiredExtensions == null)
                            {
                                requiredExtensions = new Dictionary <string, string>();
                            }
                            else if (requiredExtensions.ContainsKey(requiredExtension))
                            {
                                continue;
                            }
                            requiredExtensions.Add(requiredExtension, requiredExtension);
                        }
                    }
                }
                if (requiredExtensions != null)
                {
                    _savedChanges = ORMExtensionManager.EnsureExtensions(_projectItem, _serviceProvider, requiredExtensions.Values);
                }
            }
            if (_savedChanges)
            {
#if VISUALSTUDIO_10_0
                ProjectItemGroupElement itemGroup = _originalItemGroup;
                ProjectRootElement      project   = _project;
#else // VISUALSTUDIO_10_0
                BuildItemGroup itemGroup = _originalItemGroup;
                Microsoft.Build.BuildEngine.Project project = _project;
#endif // VISUALSTUDIO_10_0
                EnvDTE.ProjectItem projectItem    = _projectItem;
                string             sourceFileName = _sourceFileName;
                Dictionary <string, PseudoBuildItem> pseudoItems = _pseudoItemsByOutputFormat;
                IDictionary <string, IORMGenerator>  generators  =
#if VISUALSTUDIO_15_0
                    ORMCustomTool.GetORMGenerators(_serviceProvider);
#else
                    ORMCustomTool.ORMGenerators;
#endif
                PseudoBuildItem pseudoItem;
                string          generatorNameData;        // The first string is the primary generator, others are the format modifiers, space delimited
                IVsShell        shell;

                Dictionary <string, IORMGenerator> generatorsWithTargetsByOutputFormat = null;
                IDictionary <string, ORMCustomToolUtility.GeneratorTargetSet> targetSetsByFormatName = null;
                foreach (PseudoBuildItem testPseudoItem in pseudoItems.Values)
                {
                    string         primaryGeneratorName;
                    IList <string> generatorTargets;
                    IORMGenerator  generator;
                    if (!string.IsNullOrEmpty(generatorNameData = testPseudoItem.CurrentGeneratorNames) &&
                        null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData)) &&
                        generators.TryGetValue(primaryGeneratorName, out generator) &&
                        null != (generatorTargets = generator.GeneratorTargetTypes) &&
                        0 != generatorTargets.Count)
                    {
                        (generatorsWithTargetsByOutputFormat ?? (generatorsWithTargetsByOutputFormat = new Dictionary <string, IORMGenerator>(StringComparer.OrdinalIgnoreCase)))[generator.ProvidesOutputFormat] = generator;
                    }
                }
                if (generatorsWithTargetsByOutputFormat != null)
                {
                    IDictionary <string, GeneratorTarget[]> docTargets = null;
                    EnvDTE.Document projectItemDocument = projectItem.Document;
                    string          itemPath;
                    if (projectItemDocument != null)
                    {
                        using (Stream targetsStream = ORMCustomToolUtility.GetDocumentExtension <Stream>(projectItemDocument, "ORMGeneratorTargets", itemPath = projectItem.get_FileNames(0), _serviceProvider))
                        {
                            if (targetsStream != null)
                            {
                                targetsStream.Seek(0, SeekOrigin.Begin);
                                docTargets = new BinaryFormatter().Deserialize(targetsStream) as IDictionary <string, GeneratorTarget[]>;
                            }
                        }
                    }
                    else if (null != (shell = _serviceProvider.GetService(typeof(SVsShell)) as IVsShell))
                    {
                        Guid       pkgId = typeof(ORMDesignerPackage).GUID;
                        IVsPackage package;
                        if (0 != shell.IsPackageLoaded(ref pkgId, out package) || package == null)
                        {
                            shell.LoadPackage(ref pkgId, out package);
                        }

                        // Temporarily load the document so that the generator targets can be resolved.
                        using (Store store = new ModelLoader(ORMDesignerPackage.ExtensionLoader, true).Load(projectItem.get_FileNames(0)))
                        {
                            docTargets = GeneratorTarget.ConsolidateGeneratorTargets(store as IFrameworkServices);
                        }
                    }

                    // We have generators that care about targets, which means that ExpandGeneratorTargets will
                    // product placeholder targets for these generators even if docTargets is currently null.
                    // This allows the dialog to turn on a generator before the data (or even extension) to feed
                    // it is available in the model and provides a smooth transition in and out of this placeholder
                    // state. It is up to the individual generators to proceed without explicit target data or
                    // to produce a message for the user with instructions on how to add the data to the model.
                    Dictionary <string, string> generatorNamesByOutputFormat = new Dictionary <string, string>();
                    foreach (KeyValuePair <string, PseudoBuildItem> pair in pseudoItems)
                    {
                        generatorNameData = pair.Value.CurrentGeneratorNames;
                        if (!string.IsNullOrEmpty(generatorNameData))
                        {
                            generatorNamesByOutputFormat[pair.Key] = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData);
                        }
                    }
                    targetSetsByFormatName = ORMCustomToolUtility.ExpandGeneratorTargets(generatorNamesByOutputFormat, docTargets
#if VISUALSTUDIO_15_0
                                                                                         , _serviceProvider
#endif // VISUALSTUDIO_15_0
                                                                                         );
                }

                Dictionary <string, BitTracker> processedGeneratorTargets = null;
                if (targetSetsByFormatName != null)
                {
                    processedGeneratorTargets = new Dictionary <string, BitTracker>();
                    foreach (KeyValuePair <string, ORMCustomToolUtility.GeneratorTargetSet> kvp in targetSetsByFormatName)
                    {
                        processedGeneratorTargets[kvp.Key] = new BitTracker(kvp.Value.Instances.Length);
                    }
                }

                if (null != itemGroup)
                {
#if VISUALSTUDIO_10_0
                    Dictionary <string, ProjectItemElement> removedItems = null;
                    foreach (ProjectItemElement item in itemGroup.Items)
#else // VISUALSTUDIO_10_0
                    Dictionary <string, BuildItem> removedItems = null;
                    foreach (BuildItem item in itemGroup)
#endif // VISUALSTUDIO_10_0
                    {
                        string        primaryGeneratorName;
                        string        outputFormat;
                        IORMGenerator generator;
                        if (null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(item.GetEvaluatedMetadata(ITEMMETADATA_ORMGENERATOR))) &&
                            string.Equals(item.GetEvaluatedMetadata(ITEMMETADATA_DEPENDENTUPON), sourceFileName, StringComparison.OrdinalIgnoreCase) &&
                            generators.TryGetValue(primaryGeneratorName, out generator) &&
                            pseudoItems.TryGetValue(outputFormat = generator.ProvidesOutputFormat, out pseudoItem))
                        {
                            generatorNameData = pseudoItem.CurrentGeneratorNames;
                            ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                            BitTracker processedForFormat = default(BitTracker);
                            if (targetSetsByFormatName != null)
                            {
                                if (targetSetsByFormatName.TryGetValue(outputFormat, out targetSet))
                                {
                                    processedForFormat = processedGeneratorTargets[outputFormat];
                                }
                            }

                            List <PseudoBuildInstance> originalInstances;
                            bool removeInstance = false;
                            if (string.IsNullOrEmpty(generatorNameData))
                            {
                                // The item is deleted, mark for removal
                                removeInstance = true;
                            }
                            else if (null != (originalInstances = pseudoItem.OriginalInstances))
                            {
                                for (int i = 0, count = originalInstances.Count; i < count && !removeInstance; ++i)
                                {
                                    PseudoBuildInstance instance = originalInstances[i];
                                    if (instance.IsRemoved)
                                    {
                                        continue;
                                    }

                                    GeneratorTarget[] targets = instance.OriginalGeneratorTargets;
                                    if (targetSet != null)
                                    {
                                        if (targets == null)
                                        {
                                            // Remove, if a target set is available then it must be used
                                            removeInstance = true;
                                        }
                                        else
                                        {
                                            int instanceIndex = targetSet.IndexOfInstance(targets, delegate(int ignoreInstance) { return(processedForFormat[ignoreInstance]); });
                                            if (instanceIndex == -1)
                                            {
                                                removeInstance = true;
                                            }
                                            else if (!processedForFormat[instanceIndex])
                                            {
                                                if (instance.OriginalGeneratorNames != generatorNameData)
                                                {
                                                    // This is a preexisting item, update its meta information
                                                    ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                                }
                                                processedForFormat[instanceIndex]       = true;
                                                processedGeneratorTargets[outputFormat] = processedForFormat;
                                                break;
                                            }
                                        }
                                    }
                                    else if (targets != null)
                                    {
                                        // Remove, formatter changed to one that does not use a generator target
                                        removeInstance = true;
                                    }
                                    else if (instance.OriginalGeneratorNames != generatorNameData)
                                    {
                                        // This is a preexisting item, update its meta information
                                        ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                    }

                                    if (removeInstance)
                                    {
                                        instance.IsRemoved = true;
                                    }
                                }
                            }

                            if (removeInstance)
                            {
                                if (removedItems == null)
                                {
#if VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, ProjectItemElement>();
#else // VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, BuildItem>();
#endif // VISUALSTUDIO_10_0
                                }
                                removedItems[ORMCustomToolUtility.GetItemInclude(item)] = item;
                            }
                        }
                    }
                    if (removedItems != null)
                    {
                        EnvDTE.ProjectItems subItems = projectItem.ProjectItems;
#if VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, ProjectItemElement> removePair in removedItems)
                        {
                            ProjectItemElement      removeItem = removePair.Value;
                            ProjectElementContainer removeFrom;
                            if (null != (removeFrom = removeItem.Parent))
                            {
                                removeFrom.RemoveChild(removeItem);
                            }
#else // VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, BuildItem> removePair in removedItems)
                        {
                            project.RemoveItem(removePair.Value);
#endif // VISUALSTUDIO_10_0
                            try
                            {
                                EnvDTE.ProjectItem subItem = subItems.Item(removePair.Key);
                                if (subItem != null)
                                {
                                    subItem.Delete();
                                }
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                    }

#if !VISUALSTUDIO_10_0
                    // Empty item groups remove themselves from the project, we'll need
                    // to recreate below if the group is empty after the remove phase.
                    if (itemGroup.Count == 0)
                    {
                        itemGroup = null;
                    }
#endif
                }

                // Removes and changes are complete, proceed with adds for any new items
                string newItemDirectory          = null;
                string projectPath               = null;
                EnvDTE.ProjectItems projectItems = null;
                string tmpFile = null;
                // Adding a file to our special item group adds it to the build system. However,
                // it does not add it to the parallel project system, which is what displays in
                // the solution explorer. Therefore, we also explicitly add the item to the
                // project system as well. Unfortunately, this extra add automatically creates
                // a redundant item (usually in a new item group) for our adding item. Track anything
                // we add through the project system so that we can remove these redundant items from the
                // build system when we're done.
                Dictionary <string, string> sideEffectItemNames = null;
                try
                {
                    Action <IORMGenerator, string, ORMCustomToolUtility.GeneratorTargetSet, GeneratorTarget[]> addProjectItem = delegate(IORMGenerator generator, string allGenerators, ORMCustomToolUtility.GeneratorTargetSet targetSet, GeneratorTarget[] targetInstance)
                    {
                        if (itemGroup == null)
                        {
#if VISUALSTUDIO_10_0
                            itemGroup = project.AddItemGroup();
#else
                            itemGroup = project.AddNewItemGroup();
#endif
                            itemGroup.Condition = string.Concat(ITEMGROUP_CONDITIONSTART, _projectItemRelativePath, ITEMGROUP_CONDITIONEND);
                        }
                        if (newItemDirectory == null)
                        {
                            // Initialize general information
#if VISUALSTUDIO_10_0
                            projectPath = project.FullPath;
#else
                            projectPath = project.FullFileName;
#endif
                            newItemDirectory = Path.GetDirectoryName(new Uri(projectPath).MakeRelativeUri(new Uri((string)projectItem.Properties.Item("LocalPath").Value)).ToString());
                            projectItems     = projectItem.ProjectItems;
                        }

                        string defaultFileName  = generator.GetOutputFileDefaultName(sourceFileName);
                        string fileName         = targetInstance == null ? defaultFileName : ORMCustomToolUtility.GeneratorTargetSet.DecorateFileName(defaultFileName, targetInstance);
                        string fileRelativePath = Path.Combine(newItemDirectory, fileName);
                        string fileAbsolutePath = string.Concat(new FileInfo(projectPath).DirectoryName, Path.DirectorySeparatorChar, fileRelativePath);
#if VISUALSTUDIO_10_0
                        ProjectItemElement newBuildItem;
#else
                        BuildItem newBuildItem;
#endif
                        newBuildItem = generator.AddGeneratedFileItem(itemGroup, sourceFileName, fileRelativePath);

                        if (allGenerators != null)
                        {
                            ORMCustomToolUtility.SetItemMetaData(newBuildItem, ITEMMETADATA_ORMGENERATOR, allGenerators);
                        }

                        if (targetInstance != null)
                        {
                            ORMCustomToolUtility.SetGeneratorTargetMetadata(newBuildItem, targetInstance);
                        }

                        (sideEffectItemNames ?? (sideEffectItemNames = new Dictionary <string, string>()))[fileRelativePath] = null;
                        if (File.Exists(fileAbsolutePath))
                        {
                            try
                            {
                                projectItems.AddFromFile(fileAbsolutePath);
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                        else
                        {
                            if (tmpFile == null)
                            {
                                tmpFile = Path.GetTempFileName();
                            }
                            EnvDTE.ProjectItem newProjectItem = projectItems.AddFromTemplate(tmpFile, fileName);
                            string             customTool;
                            if (!string.IsNullOrEmpty(customTool = newBuildItem.GetMetadata(ITEMMETADATA_GENERATOR)))
                            {
                                newProjectItem.Properties.Item("CustomTool").Value = customTool;
                            }
                        }
                    };

                    foreach (KeyValuePair <string, PseudoBuildItem> keyedPseudoItem in pseudoItems)
                    {
                        pseudoItem = keyedPseudoItem.Value;
                        string allGenerators    = pseudoItem.CurrentGeneratorNames;
                        string primaryGenerator = ORMCustomToolUtility.GetPrimaryGeneratorName(allGenerators);
                        if (allGenerators == primaryGenerator)
                        {
                            allGenerators = null;
                        }
                        IORMGenerator generator    = generators[primaryGenerator];
                        string        outputFormat = generator.ProvidesOutputFormat;
                        ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                        if (targetSetsByFormatName != null)
                        {
                            targetSetsByFormatName.TryGetValue(outputFormat, out targetSet);
                        }

                        if (targetSet != null)
                        {
                            // OriginalInstances were already updated in the remove loop and processed
                            // instances were flagged. Find additional instances from the target set (created
                            // just now from the current model), not from the pseudoItem (created from the project
                            // files that possibly reflect a previous version of the model).
                            GeneratorTarget[][] instances = targetSet.Instances;
                            BitTracker          processed = processedGeneratorTargets[outputFormat];

                            for (int i = 0, count = instances.Length; i < count; ++i)
                            {
                                if (!processed[i])
                                {
                                    addProjectItem(generator, allGenerators, targetSet, instances[i]);
                                }
                            }
                        }
                        else if (pseudoItem.OriginalInstances == null)
                        {
                            addProjectItem(generator, allGenerators, null, null);
                        }
                        else
                        {
                            // Make sure there was an original instance that did not have a target set.
                            List <PseudoBuildInstance> originals = pseudoItem.OriginalInstances;
                            int i = 0, count = originals.Count;
                            for (; i < count; ++i)
                            {
                                if (originals[i].OriginalGeneratorTargets == null)
                                {
                                    break;
                                }
                            }

                            if (i == count)
                            {
                                addProjectItem(generator, allGenerators, null, null);
                            }
                        }
                    }
                }
                finally
                {
                    if (tmpFile != null)
                    {
                        File.Delete(tmpFile);
                    }
                }

                if (sideEffectItemNames != null)
                {
                    ORMCustomToolUtility.RemoveSideEffectItems(sideEffectItemNames, project, itemGroup);
                }

#if VISUALSTUDIO_10_0
                // Old group remove themselves when empty, but this is
                // not true in the new build system. Clean up as needed.
                if (itemGroup != null &&
                    itemGroup.Items.Count == 0)
                {
                    project.RemoveChild(itemGroup);
                }
#endif
                VSLangProj.VSProjectItem vsProjectItem = projectItem.Object as VSLangProj.VSProjectItem;
                if (vsProjectItem != null)
                {
                    vsProjectItem.RunCustomTool();
                }
            }
            base.OnClosed(e);
        }
示例#8
0
 public void RemoveItemGroupsWithMatchingCondition()
 {
     Project p = new Project();
     BuildItemGroup buildItemGroup = p.AddNewItemGroup();
     buildItemGroup.Condition = "true";
     p.AddNewItemGroup();
     Assertion.AssertEquals(2, p.ItemGroups.Count);
     p.RemoveItemGroupsWithMatchingCondition("true");
     Assertion.AssertEquals(1, p.ItemGroups.Count);
 }
示例#9
0
        /// <summary>
        /// Adds properties indicating the current solution configuration and tools version into the solution project.
        /// Also lists all the projects in the solution, as items.
        /// </summary>
        private static void AddCacheRelatedProperties(Project msbuildProject, string fullSolutionConfigurationName, string toolsVersion, ArrayList projects)
        {
            BuildPropertyGroup cachePropertyGroup = msbuildProject.AddNewPropertyGroup(false /* insertAtEndOfProject = false */);

            // Store the solution configuration, if it's available (ie., not null because it's invalid)
            if (fullSolutionConfigurationName != null)
            {
                cachePropertyGroup.AddNewProperty(cacheSolutionConfigurationPropertyName, fullSolutionConfigurationName);
            }

            // Store the tools version, too.
            cachePropertyGroup.AddNewProperty(cacheToolsVersionPropertyName, toolsVersion);

            // And the engine version, so we don't read caches written by other engines.
            cachePropertyGroup.AddNewProperty(cacheVersionNumber, Constants.AssemblyVersion);

            // And store a list of all the projects. We can use this next time for timestamp checking.
            BuildItemGroup cacheItemGroup = msbuildProject.AddNewItemGroup();
            foreach (ProjectInSolution project in projects)
            {
                // Only add projects that correspond to actual files on disk. Solution folders and web projects correspond to folders, so we don't care about them.
                if (project.ProjectType != SolutionProjectType.SolutionFolder && project.ProjectType != SolutionProjectType.WebProject)
                {
                    cacheItemGroup.AddNewItem(cacheProjectListName, EscapingUtilities.Escape(project.RelativePath)); 
                }
            }
        }
示例#10
0
 public void RemoveEvaluatedItemSuccess()
 {
     try
     {
         string includePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "*.foo");
         List<string> files = CompatibilityTestHelpers.CreateFiles(4, "foo", "foo", ObjectModelHelpers.TempProjectDir);
         Project p = new Project(new Engine());
         BuildItemGroup group = p.AddNewItemGroup();
         group.AddNewItem("foos", includePath);
         object o = p.EvaluatedItems;
         files.RemoveAt(files.IndexOf(p.EvaluatedItems[0].FinalItemSpec));
         p.RemoveItem(p.EvaluatedItems[0]);
         int i = 0;
         foreach (string fileName in files)
         {
             Assertion.AssertEquals(includePath, group[0].FinalItemSpec);
             Assertion.AssertEquals(includePath, group[0].Include);
             Assertion.AssertEquals(fileName, p.EvaluatedItems[i].Include);
             Assertion.AssertEquals(fileName, p.EvaluatedItems[i].FinalItemSpec);
             i++;
         }
     }
     finally
     {
         CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir);
     }
 }
示例#11
0
 public void RemoveEvaluatedItem1()
 {
     try
     {
         List<string> files = CompatibilityTestHelpers.CreateFiles(4, "foo", "foo", ObjectModelHelpers.TempProjectDir);
         Project p = new Project(new Engine());
         BuildItemGroup group = p.AddNewItemGroup();
         group.AddNewItem("foos", Path.Combine(ObjectModelHelpers.TempProjectDir, "*.foo"));
         object o = p.EvaluatedItems; // this causes the failure 
         group.RemoveItem(p.EvaluatedItems[0]); // Exception thrown here
         Assertion.Fail("success as failure"); // should not get here due to exception above
     }
     catch (Exception e)
     {
         if (!(e.GetType().ToString().Contains("InternalErrorException")))
         {
             Assertion.Fail(e.Message + " was thrown");
         }
         else
         {
             Assertion.Assert("InternalErrorException was thrown", true);
         }
     }
     finally
     {
         CompatibilityTestHelpers.CleanupDirectory(ObjectModelHelpers.TempProjectDir);
     }
 }
        /// <summary>
        /// Prepares the given MSBuild <see cref="Project"/> with properties and items from the given <see cref="GitHubWebhook"/>.
        /// </summary>
        /// <param name="project">The project to prepare.</param>
        /// <param name="hook">The webhook to prepare the project with.</param>
        public static void PrepareProject(Project project, GitHubWebhook hook)
        {
            BuildPropertyGroup properties = project.AddNewPropertyGroup(false);
            properties.AddNewProperty("GitHubAfter", hook.After);
            properties.AddNewProperty("GitHubBefore", hook.Before);
            properties.AddNewProperty("GitHubRef", hook.Ref);
            properties.AddNewProperty("GitHubRepositoryDescription", hook.Repository.Description);
            properties.AddNewProperty("GitHubRepositoryForks", hook.Repository.Forks.ToString(CultureInfo.InvariantCulture));
            properties.AddNewProperty("GitHubRepositoryHomepage", hook.Repository.Homepage);
            properties.AddNewProperty("GitHubRepositoryName", hook.Repository.Name);
            properties.AddNewProperty("GitHubRepositoryOwnerName", hook.Repository.Owner.Name);
            properties.AddNewProperty("GitHubRepositoryOwnerEmail", hook.Repository.Owner.Email);
            properties.AddNewProperty("GitHubRepositoryPlegie", hook.Repository.Plegie);
            properties.AddNewProperty("GitHubRepositoryPrivate", hook.Repository.Private.ToString(CultureInfo.InvariantCulture));
            properties.AddNewProperty("GitHubRepositoryUrl", hook.Repository.Url);
            properties.AddNewProperty("GitHubRepositoryWatchers", hook.Repository.Watchers.ToString(CultureInfo.InvariantCulture));

            BuildItemGroup commits = project.AddNewItemGroup();

            foreach (GitHubWebhookCommit commit in hook.Commits)
            {
                BuildItem item = commits.AddNewItem("GitHubCommit", commit.Url);
                item.SetMetadata("Id", commit.Id);
                item.SetMetadata("Message", commit.Message);
                item.SetMetadata("Timestamp", commit.Timestamp);
                item.SetMetadata("AuthorName", commit.Author.Name);
                item.SetMetadata("AuthorEmail", commit.Author.Email);
            }
        }
示例#13
0
        public override void Execute()
        {
            if (!(hostContext.Data["EnabledRenderers"] as StringCollection).Contains(this.Identifier))
            {
                return;
            }

            // Get parameters
            Dictionary <String, StringCollection> parameters = hostContext.Data["CommandParameters"] as Dictionary <String, StringCollection>;

            System.Diagnostics.Trace.WriteLine("\r\nStarting RIMBA Renderer", "information");
            StringCollection genFormatters = new StringCollection();
            bool             makeWP7Proj   = false;

            if (hostContext.Mode == Pipeline.OperationModeType.Quirks)
            {
                System.Diagnostics.Trace.WriteLine("--- WARNING ---\r\n Host context is operating in Quirks mode, GPMR cannot guarantee output will be accurate\r\n--- WARNING ---");
            }

            #region Validate all parameters
            // Validate parameters
            if (!parameters.ContainsKey("rimbapi-api-ns"))
            {
                parameters.Add("rimbapi-api-ns", new StringCollection());
                parameters["rimbapi-api-ns"].Add("MARC.Everest");
            }
            if (!parameters.ContainsKey("rimbapi-target-ns"))
            {
                parameters.Add("rimbapi-target-ns", new StringCollection());
                parameters["rimbapi-target-ns"].Add("output");
            }
            if (parameters.ContainsKey("rimbapi-root-class"))
            {
                RootClass = parameters["rimbapi-root-class"][0];
            }
            if (parameters.ContainsKey("rimbapi-gen-vocab"))
            {
                GenerateVocab = Convert.ToBoolean(parameters["rimbapi-gen-vocab"][0]);
            }
            if (parameters.ContainsKey("rimbapi-gen-rim"))
            {
                GenerateRim = Convert.ToBoolean(parameters["rimbapi-gen-rim"][0]);
            }
            if (parameters.ContainsKey("rimbapi-profileid"))
            {
                InteractionRenderer.profileId = parameters["rimbapi-profileid"][0];
            }
            if (parameters.ContainsKey("rimbapi-oid-profileid"))
            {
                InteractionRenderer.profileIdOid = parameters["rimbapi-oid-profileid"][0];
            }
            if (parameters.ContainsKey("rimbapi-oid-interactionid"))
            {
                InteractionRenderer.interactionIdOid = parameters["rimbapi-oid-interactionid"][0];
            }
            if (parameters.ContainsKey("rimbapi-oid-triggerevent"))
            {
                InteractionRenderer.triggerEventOid = parameters["rimbapi-oid-triggerevent"][0];
            }
            if (parameters.ContainsKey("rimbapi-gen-its"))
            {
                genFormatters = parameters["rimbapi-gen-its"];
            }
            if (parameters.ContainsKey("rimbapi-phone"))
            {
                makeWP7Proj = bool.Parse(parameters["rimbapi-phone"][0]);
            }

            #endregion

            // Initialize Heuristics
            MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Datatypes.Initialize(parameters["rimbapi-api-ns"][0]);
            MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Interfaces.Initialize(parameters["rimbapi-api-ns"][0]);

            // Get our repository ready
            ClassRepository classRep = hostContext.Data["SourceCR"] as ClassRepository;

            string ProjectFileName = "output.csproj"; // Set the output file name
            if (parameters.ContainsKey("rimbapi-target-ns"))
            {
                ProjectFileName = parameters["rimbapi-target-ns"][0];
            }
            if (parameters.ContainsKey("rimbapi-partials"))
            {
                RenderPartials = Boolean.Parse(parameters["rimbapi-partials"][0]);
            }
            if (parameters.ContainsKey("rimbapi-realm-pref"))
            {
                prefRealm = parameters["rimbapi-realm-pref"][0];
            }
            if (parameters.ContainsKey("rimbapi-max-literals"))
            {
                MaxLiterals = Int32.Parse(parameters["rimbapi-max-literals"][0]);
            }
            if (parameters.ContainsKey("rimbapi-suppress-doc"))
            {
                SuppressDoc = Boolean.Parse(parameters["rimbapi-suppress-doc"][0]);
            }
            // Setup the template parameters
            string[][] templateFields = new string[][]
            {
                new string[] { "$license$", parameters.ContainsKey("rimbapi-license") ? Licenses.ResourceManager.GetString(parameters["rimbapi-license"][0].ToUpper()) : "" },
                new string[] { "$org$", parameters.ContainsKey("rimbapi-org") ? parameters["rimbapi-org"][0] : "" },
                new string[] { "$date$", DateTime.Now.ToString("yyyy-MM-dd") },
                new string[] { "$clrversion$", Environment.Version.ToString() },
                new string[] { "$time$", DateTime.Now.ToString("HH:mm:ss") },
                new string[] { "$author$", SystemInformation.UserName },
                new string[] { "$year$", DateTime.Now.Year.ToString() },
                new string[] { "$version$", Assembly.GetEntryAssembly().GetName().Version.ToString() },
                new string[] { "$guid$", Guid.NewGuid().ToString() },
                new string[] { "$name$", ProjectFileName },
                new string[] { "$mrversion$", InteractionRenderer.profileId ?? "" }
            };

            // Now we want to scan our assembly for FeatureRenderers
            List <KeyValuePair <FeatureRendererAttribute, IFeatureRenderer> > renderers = new List <KeyValuePair <FeatureRendererAttribute, IFeatureRenderer> >();
            foreach (Type t in this.GetType().Assembly.GetTypes())
            {
                if (t.GetInterface("MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.Interfaces.IFeatureRenderer") != null &&
                    t.GetCustomAttributes(typeof(FeatureRendererAttribute), true).Length > 0)
                {
                    foreach (FeatureRendererAttribute feature in (t.GetCustomAttributes(typeof(FeatureRendererAttribute), true)))
                    {
                        // Only one feature renderer per feature, so if the dictionary throws an exception
                        // on the add it is ok
                        renderers.Add(new KeyValuePair <FeatureRendererAttribute, IFeatureRenderer>(feature, (IFeatureRenderer)t.Assembly.CreateInstance(t.FullName)));
                    }
                }
            }

            #region Setup the project
            // Create engine reference
            Microsoft.Build.BuildEngine.Engine engine = new Microsoft.Build.BuildEngine.Engine(
                Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v3.5")),
                                               phoneEngine = new Microsoft.Build.BuildEngine.Engine(
                Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v4.0.30319"));

            // Create MSPROJ
            Microsoft.Build.BuildEngine.Project project   = new Microsoft.Build.BuildEngine.Project(engine),
                                                phoneProj = new Project(phoneEngine, "4.0");


            phoneProj.DefaultTargets = project.DefaultTargets = "Build";


            // Setup project attributes
            Microsoft.Build.BuildEngine.BuildPropertyGroup pg = project.AddNewPropertyGroup(false);

            Microsoft.Build.BuildEngine.BuildProperty property = pg.AddNewProperty("Configuration", "Release");

            property.Condition = "'$(Configuration)' == ''";
            property           = pg.AddNewProperty("Platform", "AnyCPU");
            property.Condition = "'$(Platform)' == ''";
            pg.AddNewProperty("ProductVersion", "10.0.20506");
            pg.AddNewProperty("SchemaVersion", "2.0");
            pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString());
            pg.AddNewProperty("OutputType", "Library");
            pg.AddNewProperty("AppDesignerFolder", "Properties");
            pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]);
            pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0]);

            // Release AnyCPU
            pg           = project.AddNewPropertyGroup(false);
            pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'";
            pg.AddNewProperty("DebugType", "pdbonly");
            pg.AddNewProperty("Optimize", "true");
            pg.AddNewProperty("OutputPath", "bin\\release");
            pg.AddNewProperty("DefineConstants", "TRACE");
            pg.AddNewProperty("ErrorReport", "prompt");
            pg.AddNewProperty("WarningLevel", "4");
            pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".xml");

            // Create Dir Structure
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "bin"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "lib"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Properties"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Vocabulary"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Interaction"));

            // Add reference structure
            Microsoft.Build.BuildEngine.BuildItemGroup refItemGroup = project.AddNewItemGroup();

            // Add References
            File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.dll"), true);

            if (makeWP7Proj)
            {
                File.Copy(Path.Combine(Path.Combine(System.Windows.Forms.Application.StartupPath, "lib"), "MARC.Everest.Phone.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.Phone.dll"), true);
            }

            File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.xml"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.xml"), true);
            refItemGroup.AddNewItem("Reference", "System");
            refItemGroup.AddNewItem("Reference", "System.Drawing");
            refItemGroup.AddNewItem("Reference", "System.Xml");
            Microsoft.Build.BuildEngine.BuildItem buildItem = refItemGroup.AddNewItem("Reference", @"MARC.Everest");
            buildItem.SetMetadata("SpecificVersion", "false");
            buildItem.SetMetadata("HintPath", "lib\\MARC.Everest.dll");

            project.AddNewImport("$(MSBuildBinPath)\\Microsoft.CSharp.targets", null);

            Microsoft.Build.BuildEngine.BuildItemGroup fileItemGroup      = project.AddNewItemGroup(),
                                                       phoneFileItemGroup = phoneProj.AddNewItemGroup();

            #region Assembly Info
            try
            {
                TextWriter tw = File.CreateText(Path.Combine(Path.Combine(hostContext.Output, "Properties"), "AssemblyInfo.cs"));
                try
                {
                    string Header = Template.AssemblyInfo; // Set the header to the default

                    // Populate template fields
                    foreach (String[] st in templateFields)
                    {
                        Header = Header.Replace(st[0], st[1]);
                    }

                    // Write header
                    tw.Write(Header);
                }
                finally
                {
                    tw.Close();
                }
                fileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs"));
                phoneFileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs"));
            }
            catch (Exception)
            {
                System.Diagnostics.Trace.WriteLine("Couldn't generate the AssemblyInfo.cs file for this project", "warn");
            }
            #endregion
            #endregion

            #region Code Create
            // Convert class rep to list
            List <Feature> features = new List <Feature>();
            foreach (KeyValuePair <String, Feature> kv in classRep)
            {
                features.Add(kv.Value);
            }
            // Sort so classes are processed first
            features.Sort(delegate(Feature a, Feature b)
            {
                if ((a is SubSystem) && !(b is SubSystem))
                {
                    return(-1);
                }
                else if ((b is SubSystem) && !(a is SubSystem))
                {
                    return(1);
                }
                else
                {
                    return(a.GetType().Name.CompareTo(b.GetType().Name));
                }
            });

            RenderFeatureList(features, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Any added features?
            // HACK: This should be fixed soon, but meh... I'll get around to it
            List <Feature> addlFeatures = new List <Feature>();
            foreach (KeyValuePair <String, Feature> kv in classRep)
            {
                if (!features.Contains(kv.Value))
                {
                    addlFeatures.Add(kv.Value);
                }
            }
            RenderFeatureList(addlFeatures, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Save the project
            project.Save(Path.Combine(hostContext.Output, ProjectFileName) + ".csproj");
            #endregion

            // Compile?
            #region Compile this project

            // Does the user want to compile?
            if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
            {
                string logPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); // Create log
                Microsoft.Build.BuildEngine.FileLogger logger = new Microsoft.Build.BuildEngine.FileLogger();
                logger.Parameters = "logfile=" + logPath;
                engine.RegisterLogger(logger);

                System.Diagnostics.Trace.Write(String.Format("Compiling project (Build log {0})...", logPath), "information");

                // Compile
                if (engine.BuildProject(project))
                {
                    System.Diagnostics.Trace.WriteLine("Success!", "information");
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine("Fail", "information");
                    throw new InvalidOperationException("Failed compilation, operation cannot continue");
                }
                engine.UnregisterAllLoggers();
            }
            #endregion

            #region Windows Phone

            if (makeWP7Proj)
            {
                // Setup project attributes
                pg                 = phoneProj.AddNewPropertyGroup(false);
                property           = pg.AddNewProperty("Configuration", "Release");
                property.Condition = "'$(Configuration)' == ''";
                property           = pg.AddNewProperty("Platform", "AnyCPU");
                property.Condition = "'$(Platform)' == ''";
                pg.AddNewProperty("ProductVersion", "10.0.20506");
                pg.AddNewProperty("SchemaVersion", "2.0");
                pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString());
                pg.AddNewProperty("OutputType", "Library");
                pg.AddNewProperty("AppDesignerFolder", "Properties");
                pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]);
                pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0] + ".Phone");
                pg.AddNewProperty("ProjectTypeGuids", "{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}");
                pg.AddNewProperty("TargetFrameworkVersion", "v4.0");
                pg.AddNewProperty("SilverlightVersion", "$(TargetFrameworkVersion)");
                pg.AddNewProperty("TargetFrameworkProfile", "WindowsPhone71");
                pg.AddNewProperty("TargetFrameworkIdentifier", "Silverlight");
                pg.AddNewProperty("SilverlightApplication", "false");
                pg.AddNewProperty("ValidateXaml", "true");
                pg.AddNewProperty("ThrowErrorsInValidation", "true");

                // Release AnyCPU
                pg           = phoneProj.AddNewPropertyGroup(false);
                pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'";
                pg.AddNewProperty("DebugType", "pdbonly");
                pg.AddNewProperty("Optimize", "true");
                pg.AddNewProperty("OutputPath", "bin\\release");
                pg.AddNewProperty("DefineConstants", "TRACE;SILVERLIGHT;WINDOWS_PHONE");
                pg.AddNewProperty("ErrorReport", "prompt");
                pg.AddNewProperty("NoStdLib", "true");
                pg.AddNewProperty("NoConfig", "true");
                pg.AddNewProperty("WarningLevel", "4");
                pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".Phone.xml");

                // Add reference structure
                refItemGroup = phoneProj.AddNewItemGroup();
                refItemGroup.AddNewItem("Reference", "System");
                refItemGroup.AddNewItem("Reference", "System.Xml");

                BuildItem evReference = refItemGroup.AddNewItem("Reference", @"MARC.Everest.Phone");
                evReference.SetMetadata("SpecificVersion", "false");
                evReference.SetMetadata("HintPath", "lib\\MARC.Everest.Phone.dll");

                // Add WP7 Imports
                phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets", null);
                phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets", null);

                // HACK: Add tools version
                string fileName = Path.Combine(hostContext.Output, ProjectFileName) + ".Phone.csproj";
                phoneProj.Save(fileName);
                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);
                doc.DocumentElement.Attributes.Append(doc.CreateAttribute("ToolsVersion"));
                doc.DocumentElement.Attributes["ToolsVersion"].Value = "4.0";
                doc.Save(fileName);

                if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
                {
                    System.Diagnostics.Trace.Write(String.Format("Compiling phone project..."), "information");

                    // Compile
                    if (phoneEngine.BuildProjectFile(fileName))
                    {
                        System.Diagnostics.Trace.WriteLine("Success!", "information");
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine("Fail", "information");
                        throw new InvalidOperationException("Failed compilation, operation cannot continue");
                    }
                }
            }

            #endregion

            #region Generate Formatter Assemblies

            // Generate the formatter assemblies
            if (genFormatters.Count > 0 && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
            {
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                Trace.WriteLine("Generating ITS Formatter Types:", "information");

                // Load the assembly
                Assembly genAsm = Assembly.LoadFile(Path.Combine(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"), ProjectFileName + ".dll"));
                foreach (string s in genFormatters)
                {
                    GenerateFormatterAssembly(s, genAsm, InteractionRenderer.profileId ?? "formatter");
                }

                // Assembly resolve
                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            }
            else if (genFormatters.Count > 0)
            {
                Trace.WriteLine("Can't use --rimbapi-gen-its when --rimbapi-compile is not true, skipping ITS generation", "warn");
            }
            #endregion

            // Does the user only want asm?
            #region dllonly
            if (parameters.ContainsKey("rimbapi-dllonly") && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-dllonly"][0]))
            {
                try
                {
                    // Move the assemblies up to root
                    foreach (string file in Directory.GetFiles(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release")))
                    {
                        if (File.Exists(Path.Combine(hostContext.Output, Path.GetFileName(file))))
                        {
                            File.Delete(Path.Combine(hostContext.Output, Path.GetFileName(file)));
                        }
                        File.Move(file, Path.Combine(hostContext.Output, Path.GetFileName(file)));
                    }

                    // Clean all in the projects and remove all directories
                    List <String> directories = new List <string>(new string[] {
                        Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"),
                        Path.Combine(hostContext.Output, "bin"),
                        Path.Combine(hostContext.Output, "lib"),
                        Path.Combine(hostContext.Output, "Vocabulary"),
                        Path.Combine(hostContext.Output, "Interaction"),
                        Path.Combine(hostContext.Output, "obj")
                    });

                    // Gather files and clean
                    foreach (Microsoft.Build.BuildEngine.BuildItem fi in fileItemGroup)
                    {
                        // Add directory on the "to be deleted"
                        string dirName = Path.GetDirectoryName(Path.Combine(hostContext.Output, fi.Include));
                        if (!directories.Contains(dirName))
                        {
                            directories.Add(dirName);
                        }

                        Trace.WriteLine(String.Format("Deleting {0}...", fi.Include), "debug");
                        File.Delete(Path.Combine(hostContext.Output, fi.Include));
                    }
                    // Clean dirs
                    foreach (string s in directories)
                    {
                        Directory.Delete(s, true);
                    }
                    File.Delete(project.FullFileName);
                }
                catch (Exception)
                {
                    System.Diagnostics.Trace.WriteLine("Could not clean working files!", "warn");
                }
            }
            #endregion
        }
 public override void AddNewItem(Project project, string name, string include)
 {
     project.AddNewItemGroup().AddNewItem(name, include);
 }
        protected virtual void ConfigureProject(Project proj)
        {
            _globalProperties = proj.AddNewPropertyGroup(false);
            _globalProperties.AddNewProperty("OutputType", "Library");
            _globalProperties.AddNewProperty("AssemblyName", AssemblyName);
            _globalProperties.AddNewProperty("OutputPath", OutputPath);
            _globalProperties.AddNewProperty("Optimize", "true");
            _globalProperties.AddNewProperty("NoWarn", "1591,0168");
            _globalProperties.AddNewProperty("DocumentationFile", string.Concat(OutputPath, "\\", AssemblyName, ".XML"));
            proj.AddNewImport(@"$(MSBuildBinPath)\Microsoft.CSharp.targets", String.Empty);

            _references = proj.AddNewItemGroup();
        }
示例#16
0
        public override void Execute()
        {
            if (!(hostContext.Data["EnabledRenderers"] as StringCollection).Contains(this.Identifier)) return;

            // Get parameters
            Dictionary<String, StringCollection> parameters = hostContext.Data["CommandParameters"] as Dictionary<String, StringCollection>;
            System.Diagnostics.Trace.WriteLine("\r\nStarting RIMBA Renderer", "information");
            StringCollection genFormatters = new StringCollection();
            bool makeWP7Proj = false;

            if (hostContext.Mode == Pipeline.OperationModeType.Quirks)
                System.Diagnostics.Trace.WriteLine("--- WARNING ---\r\n Host context is operating in Quirks mode, GPMR cannot guarantee output will be accurate\r\n--- WARNING ---");

            #region Validate all parameters
            // Validate parameters
            if (!parameters.ContainsKey("rimbapi-api-ns"))
            {
                parameters.Add("rimbapi-api-ns", new StringCollection());
                parameters["rimbapi-api-ns"].Add("MARC.Everest");
            }
            if (!parameters.ContainsKey("rimbapi-target-ns"))
            {
                parameters.Add("rimbapi-target-ns", new StringCollection());
                parameters["rimbapi-target-ns"].Add("output");
            }
            if (parameters.ContainsKey("rimbapi-root-class"))
                RootClass = parameters["rimbapi-root-class"][0];
            if (parameters.ContainsKey("rimbapi-gen-vocab"))
                GenerateVocab = Convert.ToBoolean(parameters["rimbapi-gen-vocab"][0]);
            if(parameters.ContainsKey("rimbapi-gen-rim"))
                GenerateRim = Convert.ToBoolean(parameters["rimbapi-gen-rim"][0]);
            if (parameters.ContainsKey("rimbapi-profileid"))
                InteractionRenderer.profileId = parameters["rimbapi-profileid"][0];
            if (parameters.ContainsKey("rimbapi-oid-profileid"))
                InteractionRenderer.profileIdOid = parameters["rimbapi-oid-profileid"][0];
            if (parameters.ContainsKey("rimbapi-oid-interactionid"))
                InteractionRenderer.interactionIdOid = parameters["rimbapi-oid-interactionid"][0];
            if (parameters.ContainsKey("rimbapi-oid-triggerevent"))
                InteractionRenderer.triggerEventOid = parameters["rimbapi-oid-triggerevent"][0];
            if (parameters.ContainsKey("rimbapi-gen-its"))
                genFormatters = parameters["rimbapi-gen-its"];
            if (parameters.ContainsKey("rimbapi-phone"))
                makeWP7Proj = bool.Parse(parameters["rimbapi-phone"][0]);

            #endregion

            // Initialize Heuristics
            MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Datatypes.Initialize(parameters["rimbapi-api-ns"][0]);
            MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.HeuristicEngine.Interfaces.Initialize(parameters["rimbapi-api-ns"][0]);

            // Get our repository ready
            ClassRepository classRep = hostContext.Data["SourceCR"] as ClassRepository;

            string ProjectFileName = "output.csproj"; // Set the output file name
            if (parameters.ContainsKey("rimbapi-target-ns"))
                ProjectFileName = parameters["rimbapi-target-ns"][0];
            if(parameters.ContainsKey("rimbapi-partials"))
                RenderPartials = Boolean.Parse(parameters["rimbapi-partials"][0]);
            if (parameters.ContainsKey("rimbapi-realm-pref"))
                prefRealm = parameters["rimbapi-realm-pref"][0];
            if (parameters.ContainsKey("rimbapi-max-literals"))
                MaxLiterals = Int32.Parse(parameters["rimbapi-max-literals"][0]);
            if (parameters.ContainsKey("rimbapi-suppress-doc"))
                SuppressDoc = Boolean.Parse(parameters["rimbapi-suppress-doc"][0]);
            // Setup the template parameters
            string[][] templateFields = new string[][] 
            {
                new string[] { "$license$", parameters.ContainsKey("rimbapi-license") ? Licenses.ResourceManager.GetString(parameters["rimbapi-license"][0].ToUpper()) : "" },
                new string[] { "$org$", parameters.ContainsKey("rimbapi-org") ? parameters["rimbapi-org"][0] : "" },
                new string[] { "$date$", DateTime.Now.ToString("yyyy-MM-dd") },
                new string[] { "$clrversion$", Environment.Version.ToString() },
                new string[] { "$time$", DateTime.Now.ToString("HH:mm:ss") },
                new string[] { "$author$", SystemInformation.UserName },
                new string[] { "$year$", DateTime.Now.Year.ToString() },
                new string[] { "$version$", Assembly.GetEntryAssembly().GetName().Version.ToString() },
                new string[] { "$guid$", Guid.NewGuid().ToString() }, 
                new string[] { "$name$", ProjectFileName },
                new string[] { "$mrversion$", InteractionRenderer.profileId ?? "" }
            };

            // Now we want to scan our assembly for FeatureRenderers
            List<KeyValuePair<FeatureRendererAttribute, IFeatureRenderer>> renderers = new List<KeyValuePair<FeatureRendererAttribute, IFeatureRenderer>>();
            foreach(Type t in this.GetType().Assembly.GetTypes())
                if (t.GetInterface("MohawkCollege.EHR.gpmr.Pipeline.Renderer.RimbaCS.Interfaces.IFeatureRenderer") != null &&
                    t.GetCustomAttributes(typeof(FeatureRendererAttribute), true).Length > 0)
                {
                    foreach(FeatureRendererAttribute feature in (t.GetCustomAttributes(typeof(FeatureRendererAttribute), true)))
                    {
                            // Only one feature renderer per feature, so if the dictionary throws an exception
                            // on the add it is ok
                            renderers.Add(new KeyValuePair<FeatureRendererAttribute,IFeatureRenderer>(feature, (IFeatureRenderer)t.Assembly.CreateInstance(t.FullName)));
                    }
                }

            #region Setup the project
            // Create engine reference
            Microsoft.Build.BuildEngine.Engine engine = new Microsoft.Build.BuildEngine.Engine(
                Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v3.5")),
                phoneEngine = new Microsoft.Build.BuildEngine.Engine(
                Path.Combine(Path.Combine(Path.Combine(System.Environment.SystemDirectory, "..\\Microsoft.NET"), "Framework"), "v4.0.30319"));
            
            // Create MSPROJ
            Microsoft.Build.BuildEngine.Project project = new Microsoft.Build.BuildEngine.Project(engine),
                phoneProj = new Project(phoneEngine, "4.0");

            
            phoneProj.DefaultTargets = project.DefaultTargets = "Build";
            

            // Setup project attributes
            Microsoft.Build.BuildEngine.BuildPropertyGroup pg = project.AddNewPropertyGroup(false);

            Microsoft.Build.BuildEngine.BuildProperty property = pg.AddNewProperty("Configuration", "Release");

            property.Condition = "'$(Configuration)' == ''";
            property = pg.AddNewProperty("Platform", "AnyCPU");
            property.Condition = "'$(Platform)' == ''";
            pg.AddNewProperty("ProductVersion", "10.0.20506");
            pg.AddNewProperty("SchemaVersion", "2.0");
            pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString());
            pg.AddNewProperty("OutputType", "Library");
            pg.AddNewProperty("AppDesignerFolder", "Properties");
            pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]);
            pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0]);
            
            // Release AnyCPU
            pg = project.AddNewPropertyGroup(false);
            pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'";
            pg.AddNewProperty("DebugType", "pdbonly");
            pg.AddNewProperty("Optimize", "true");
            pg.AddNewProperty("OutputPath", "bin\\release");
            pg.AddNewProperty("DefineConstants", "TRACE");
            pg.AddNewProperty("ErrorReport", "prompt");
            pg.AddNewProperty("WarningLevel", "4");
            pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".xml");

            // Create Dir Structure
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "bin"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "lib"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Properties"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Vocabulary"));
            Directory.CreateDirectory(Path.Combine(hostContext.Output, "Interaction"));

            // Add reference structure
            Microsoft.Build.BuildEngine.BuildItemGroup refItemGroup = project.AddNewItemGroup();

            // Add References
            File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.dll"), true);

            if(makeWP7Proj)
                File.Copy(Path.Combine(Path.Combine(System.Windows.Forms.Application.StartupPath, "lib"), "MARC.Everest.Phone.dll"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.Phone.dll"), true);

            File.Copy(Path.Combine(System.Windows.Forms.Application.StartupPath, "MARC.Everest.xml"), Path.Combine(Path.Combine(hostContext.Output, "lib"), "MARC.Everest.xml"), true);
            refItemGroup.AddNewItem("Reference", "System");
            refItemGroup.AddNewItem("Reference", "System.Drawing");
            refItemGroup.AddNewItem("Reference", "System.Xml");
            Microsoft.Build.BuildEngine.BuildItem buildItem = refItemGroup.AddNewItem("Reference", @"MARC.Everest");
            buildItem.SetMetadata("SpecificVersion", "false");
            buildItem.SetMetadata("HintPath", "lib\\MARC.Everest.dll");

            project.AddNewImport("$(MSBuildBinPath)\\Microsoft.CSharp.targets", null);

            Microsoft.Build.BuildEngine.BuildItemGroup fileItemGroup = project.AddNewItemGroup(),
                phoneFileItemGroup = phoneProj.AddNewItemGroup();

            #region Assembly Info
            try
            {
                TextWriter tw = File.CreateText(Path.Combine(Path.Combine(hostContext.Output, "Properties"), "AssemblyInfo.cs"));
                try
                {
                    string Header = Template.AssemblyInfo; // Set the header to the default

                    // Populate template fields
                    foreach (String[] st in templateFields)
                        Header = Header.Replace(st[0], st[1]);

                    // Write header
                    tw.Write(Header);
                }
                finally
                {
                    tw.Close();
                }
                fileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs"));
                phoneFileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs"));
            }
            catch(Exception)
            {
                System.Diagnostics.Trace.WriteLine("Couldn't generate the AssemblyInfo.cs file for this project", "warn");
            }
            #endregion
            #endregion

            #region Code Create
            // Convert class rep to list
            List<Feature> features = new List<Feature>();
            foreach (KeyValuePair<String, Feature> kv in classRep)
                features.Add(kv.Value);
            // Sort so classes are processed first
            features.Sort(delegate(Feature a, Feature b)
            {
                if ((a is SubSystem) && !(b is SubSystem)) return -1;
                else if ((b is SubSystem) && !(a is SubSystem)) return 1;
                else return a.GetType().Name.CompareTo(b.GetType().Name);
            });

            RenderFeatureList(features, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Any added features?
            // HACK: This should be fixed soon, but meh... I'll get around to it
            List<Feature> addlFeatures = new List<Feature>();
            foreach (KeyValuePair<String, Feature> kv in classRep)
                if(!features.Contains(kv.Value))
                    addlFeatures.Add(kv.Value);
            RenderFeatureList(addlFeatures, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Save the project
            project.Save(Path.Combine(hostContext.Output, ProjectFileName) + ".csproj");
            #endregion

            // Compile?
            #region Compile this project

            // Does the user want to compile?
            if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
            {
                string logPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); // Create log
                Microsoft.Build.BuildEngine.FileLogger logger = new Microsoft.Build.BuildEngine.FileLogger();
                logger.Parameters = "logfile=" + logPath;
                engine.RegisterLogger(logger);

                System.Diagnostics.Trace.Write(String.Format("Compiling project (Build log {0})...", logPath), "information");

                // Compile
                if (engine.BuildProject(project))
                    System.Diagnostics.Trace.WriteLine("Success!", "information");
                else
                {
                    System.Diagnostics.Trace.WriteLine("Fail", "information");
                    throw new InvalidOperationException("Failed compilation, operation cannot continue");

                }
                engine.UnregisterAllLoggers();
                
            }
            #endregion

            #region Windows Phone

            if (makeWP7Proj)
            {

                // Setup project attributes
                pg = phoneProj.AddNewPropertyGroup(false);
                property = pg.AddNewProperty("Configuration", "Release");
                property.Condition = "'$(Configuration)' == ''";
                property = pg.AddNewProperty("Platform", "AnyCPU");
                property.Condition = "'$(Platform)' == ''";
                pg.AddNewProperty("ProductVersion", "10.0.20506");
                pg.AddNewProperty("SchemaVersion", "2.0");
                pg.AddNewProperty("ProjectGuid", Guid.NewGuid().ToString());
                pg.AddNewProperty("OutputType", "Library");
                pg.AddNewProperty("AppDesignerFolder", "Properties");
                pg.AddNewProperty("RootNamespace", parameters["rimbapi-target-ns"][0]);
                pg.AddNewProperty("AssemblyName", parameters["rimbapi-target-ns"][0] + ".Phone");
                pg.AddNewProperty("ProjectTypeGuids", "{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}");
                pg.AddNewProperty("TargetFrameworkVersion", "v4.0");
                pg.AddNewProperty("SilverlightVersion", "$(TargetFrameworkVersion)");
                pg.AddNewProperty("TargetFrameworkProfile", "WindowsPhone71");
                pg.AddNewProperty("TargetFrameworkIdentifier", "Silverlight");
                pg.AddNewProperty("SilverlightApplication", "false");
                pg.AddNewProperty("ValidateXaml", "true");
                pg.AddNewProperty("ThrowErrorsInValidation", "true");

                // Release AnyCPU
                pg = phoneProj.AddNewPropertyGroup(false);
                pg.Condition = "'$(Configuration)|$(Platform)' == 'Release|AnyCPU'";
                pg.AddNewProperty("DebugType", "pdbonly");
                pg.AddNewProperty("Optimize", "true");
                pg.AddNewProperty("OutputPath", "bin\\release");
                pg.AddNewProperty("DefineConstants", "TRACE;SILVERLIGHT;WINDOWS_PHONE");
                pg.AddNewProperty("ErrorReport", "prompt");
                pg.AddNewProperty("NoStdLib", "true");
                pg.AddNewProperty("NoConfig", "true");
                pg.AddNewProperty("WarningLevel", "4");
                pg.AddNewProperty("DocumentationFile", "bin\\release\\" + parameters["rimbapi-target-ns"][0] + ".Phone.xml");

                // Add reference structure
                refItemGroup = phoneProj.AddNewItemGroup();
                refItemGroup.AddNewItem("Reference", "System");
                refItemGroup.AddNewItem("Reference", "System.Xml");

                BuildItem evReference = refItemGroup.AddNewItem("Reference", @"MARC.Everest.Phone");
                evReference.SetMetadata("SpecificVersion", "false");
                evReference.SetMetadata("HintPath", "lib\\MARC.Everest.Phone.dll");

                // Add WP7 Imports
                phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets", null);
                phoneProj.AddNewImport(@"$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets", null);

                // HACK: Add tools version
                string fileName = Path.Combine(hostContext.Output, ProjectFileName) + ".Phone.csproj";
                phoneProj.Save(fileName);
                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);
                doc.DocumentElement.Attributes.Append(doc.CreateAttribute("ToolsVersion"));
                doc.DocumentElement.Attributes["ToolsVersion"].Value = "4.0";
                doc.Save(fileName);

                if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
                {
                    System.Diagnostics.Trace.Write(String.Format("Compiling phone project..."), "information");

                    // Compile
                    if (phoneEngine.BuildProjectFile(fileName))
                        System.Diagnostics.Trace.WriteLine("Success!", "information");
                    else
                    {
                        System.Diagnostics.Trace.WriteLine("Fail", "information");
                        throw new InvalidOperationException("Failed compilation, operation cannot continue");

                    }
                }
            }

            #endregion

            #region Generate Formatter Assemblies

            // Generate the formatter assemblies
            if (genFormatters.Count > 0 && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
            {
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                Trace.WriteLine("Generating ITS Formatter Types:", "information");

                // Load the assembly
                Assembly genAsm = Assembly.LoadFile(Path.Combine(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"), ProjectFileName + ".dll"));
                foreach (string s in genFormatters)
                    GenerateFormatterAssembly(s, genAsm, InteractionRenderer.profileId ?? "formatter");
                
                // Assembly resolve
                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            }
            else if (genFormatters.Count > 0)
                Trace.WriteLine("Can't use --rimbapi-gen-its when --rimbapi-compile is not true, skipping ITS generation", "warn");
            #endregion

            // Does the user only want asm?
            #region dllonly
            if (parameters.ContainsKey("rimbapi-dllonly") && parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-dllonly"][0]))
                try
                {
                    // Move the assemblies up to root
                    foreach (string file in Directory.GetFiles(Path.Combine(Path.Combine(hostContext.Output, "bin"), "release")))
                    {
                        if (File.Exists(Path.Combine(hostContext.Output, Path.GetFileName(file))))
                            File.Delete(Path.Combine(hostContext.Output, Path.GetFileName(file)));
                        File.Move(file, Path.Combine(hostContext.Output, Path.GetFileName(file)));
                    }

                    // Clean all in the projects and remove all directories
                    List<String> directories = new List<string>(new string[] {
                        Path.Combine(Path.Combine(hostContext.Output, "bin"), "release"), 
                        Path.Combine(hostContext.Output, "bin"), 
                        Path.Combine(hostContext.Output, "lib"),
                        Path.Combine(hostContext.Output, "Vocabulary"), 
                        Path.Combine(hostContext.Output, "Interaction"),
                        Path.Combine(hostContext.Output, "obj")
                    });

                    // Gather files and clean
                    foreach (Microsoft.Build.BuildEngine.BuildItem fi in fileItemGroup)
                    {
                        // Add directory on the "to be deleted"
                        string dirName = Path.GetDirectoryName(Path.Combine(hostContext.Output, fi.Include));
                        if (!directories.Contains(dirName))
                            directories.Add(dirName);

                        Trace.WriteLine(String.Format("Deleting {0}...", fi.Include), "debug");
                        File.Delete(Path.Combine(hostContext.Output, fi.Include));
                    }
                    // Clean dirs
                    foreach (string s in directories)
                        Directory.Delete(s, true);
                    File.Delete(project.FullFileName);
                }
                catch(Exception)
                {
                    System.Diagnostics.Trace.WriteLine("Could not clean working files!", "warn");
                }
            #endregion

        }
示例#17
0
        public void ICollectionMethodsOnItemPropertyGroupCollection()
        {
            Engine engine = new Engine(@"C:\");
            Project project = new Project(engine);
            BuildPropertyGroup pg1 = project.AddNewPropertyGroup(true);
            BuildPropertyGroup pg2 = project.AddNewPropertyGroup(true);
            BuildItemGroup ig1 = project.AddNewItemGroup();
            BuildItemGroup ig2 = project.AddNewItemGroup();

            BuildPropertyGroup[] pgarray = new BuildPropertyGroup[2];
            BuildItemGroup[] igarray = new BuildItemGroup[2];

            project.PropertyGroups.CopyTo(pgarray, 0);
            project.ItemGroups.CopyTo(igarray, 0);

            Assertion.Assert(pgarray[0] == pg1 || pgarray[1] == pg1);
            Assertion.Assert(pgarray[0] == pg2 || pgarray[1] == pg2);

            Assertion.Assert(igarray[0] == ig1 || igarray[1] == ig1);
            Assertion.Assert(igarray[0] == ig2 || igarray[1] == ig2);
        }
示例#18
0
        /// <summary>
        /// Add a target for a project into the XML doc that's being generated.
        /// </summary>
        /// <param name="msbuildProject"></param>
        /// <param name="solution"></param>
        /// <param name="proj"></param>
        /// <param name="targetOutputItemName">The name of the item exposing this target's outputs.  May be null.</param>        
        /// <param name="subTargetName"></param>
        /// <owner>RGoel, LukaszG</owner>
        static private void AddTargetForManagedProject
        (
            Project msbuildProject,
            SolutionParser solution,
            ProjectInSolution proj,
            string targetOutputItemName,
            string subTargetName
        )
        {
            string targetName = ProjectInSolution.DisambiguateProjectTargetName(proj.GetUniqueProjectName());
            if (subTargetName != null && subTargetName.Length > 0)
            {
                targetName = targetName + ":" + subTargetName;
            }

            Target newTarget = msbuildProject.Targets.AddNewTarget(targetName);
            newTarget.DependsOnTargets = GetProjectDependencies(proj.ParentSolution, proj, subTargetName);
            newTarget.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";

            if (!String.IsNullOrEmpty(targetOutputItemName))
            {
                newTarget.TargetElement.SetAttribute("Outputs", string.Format(CultureInfo.InvariantCulture, "@({0})", targetOutputItemName));
            }
            
            // Only create build items if we're called with the null subtarget. We're getting called
            // a total of four times and only want to create the build items once.
            bool createBuildItems = (subTargetName == null);

            foreach (ConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
            {
                ProjectConfigurationInSolution projectConfiguration = null;
                string condition = GetConditionStringForConfiguration(solutionConfiguration);

                // Create the build item group for this configuration if we haven't already
                if (solutionConfiguration.ProjectBuildItems == null)
                {
                    solutionConfiguration.ProjectBuildItems = msbuildProject.AddNewItemGroup();
                    solutionConfiguration.ProjectBuildItems.Condition = condition;
                }

                if (proj.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out projectConfiguration))
                {
                    if (projectConfiguration.IncludeInBuild)
                    {
                        // We want to specify ToolsVersion on the MSBuild task only if the solution
                        // is building with a non-Whidbey toolset, because the Whidbey MSBuild task
                        // does not support the ToolsVersion parameter.  If the user explicitly requested
                        // the 2.0 toolset be used to build the solution while specifying some value
                        // for the ProjectToolsVersion property, then one of the InitialTargets should
                        // have produced an error before reaching this point.
                        // PERF: We could emit two <MSBuild> tasks, with a condition on them. But this doubles the size of
                        // the solution wrapper project, and the cost is too high. The consequence is that when solution wrapper
                        // projects are emitted to disk (with MSBUILDEMITSOLUION=1) they cannot be reused for tools version v2.0.
                        bool specifyProjectToolsVersion = 
                            String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase) ? false : true;

                        BuildTask msbuildTask = AddMSBuildTaskElement(newTarget, proj.RelativePath, subTargetName,
                            projectConfiguration.ConfigurationName, projectConfiguration.PlatformName, specifyProjectToolsVersion);
                        msbuildTask.Condition = condition;

                        if (!String.IsNullOrEmpty(targetOutputItemName))
                        {
                            msbuildTask.AddOutputItem("TargetOutputs", targetOutputItemName);
                        }

                        if (createBuildItems)
                        {
                            string baseItemName = "BuildLevel" + proj.DependencyLevel;
                            BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.RelativePath, true /* treat as literal */);

                            projectItem.SetMetadata("Configuration", EscapingUtilities.Escape(projectConfiguration.ConfigurationName));
                            projectItem.SetMetadata("Platform", EscapingUtilities.Escape(projectConfiguration.PlatformName));
                        }
                    }
                    else
                    {
                        BuildTask messageTask = AddErrorWarningMessageElement(newTarget, XMakeElements.message, true, "SolutionProjectSkippedForBuilding", proj.ProjectName, solutionConfiguration.FullName);
                        messageTask.Condition = condition;

                        if (createBuildItems)
                        {
                            string baseItemName = "SkipLevel" + proj.DependencyLevel;
                            BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.ProjectName, true /* treat as literal */);
                        }
                    }
                }
                else
                {
                    BuildTask warningTask = AddErrorWarningMessageElement(newTarget, XMakeElements.warning, true, "SolutionProjectConfigurationMissing", proj.ProjectName, solutionConfiguration.FullName);
                    warningTask.Condition = condition;

                    if (createBuildItems)
                    {
                        string baseItemName = "MissingConfigLevel" + proj.DependencyLevel;
                        BuildItem projectItem = solutionConfiguration.ProjectBuildItems.AddNewItem(baseItemName, proj.ProjectName, true /* treat as literal */);
                    }
                }
            }
        }
示例#19
0
 public void RemoveItemGroup_Imported()
 {
     Project p = new Project();
     Project i = new Project(p.ParentEngine);
     BuildItemGroup buildItemGroup = i.AddNewItemGroup();
     p.RemoveItemGroup(buildItemGroup);
 }