Beispiel #1
0
        public void SetUp()
        {
            // Whole bunch of setup code.
            XmlElement taskNode = new XmlDocument().CreateElement("MockTask");
            LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));
            engine = new Engine(@"c:\");
            Project project = new Project(engine);
            EngineCallback engineCallback = new EngineCallback(engine);
            taskExecutionModule = new MockTaskExecutionModule(engineCallback);
            int handleId = engineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
            TaskEngine taskEngine = new TaskEngine
                                (
                                    taskNode,
                                    null, /* host object */
                                    "In Memory",
                                    project.FullFileName,
                                    engine.LoggingServices,
                                    handleId,
                                    taskExecutionModule,
                                    null
                                );
            taskEngine.TaskClass = taskClass;

            engineProxy = new EngineProxy(taskExecutionModule, handleId, project.FullFileName, project.FullFileName, engine.LoggingServices, null);
            taskExecutionModule2 = new MockTaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode);
            engineProxy2 = new EngineProxy(taskExecutionModule2, handleId, project.FullFileName, project.FullFileName, engine.LoggingServices, null);

        }
		private static Engine CreateEngine(FrameworkVersions toolsVersion, string frameworkPath)
        {
			Engine engine = new Engine(frameworkPath);

			Version fullVersion = engine.GetType().Assembly.GetName().Version;
			string version = fullVersion.ToString(2);
			if (toolsVersion == FrameworkVersions.v30 && version == "2.0")
				version = "3.0";//these use the same build runtime: 2.0/3.0
		    if (toolsVersion == FrameworkVersions.v45 && version == "4.0")
                version = "4.5";//these use the same build runtime: 4.0/4.5

			if (version.Replace(".", "") != toolsVersion.ToString().TrimStart('v'))
                throw new ApplicationException(String.Format("Expected runtime {0}, found ({1}){2}.", toolsVersion, version, fullVersion));

            Log.Verbose("Using build engine: {0}", engine.GetType().Assembly.FullName);

			if (toolsVersion == FrameworkVersions.v20 || toolsVersion == FrameworkVersions.v30)
				engine.GlobalProperties.SetProperty("MSBuildToolsPath", frameworkPath);

			//<property name="FrameworkSDKDir" value="%ProgramFiles%\Microsoft.NET\SDK\v2.0\" global="true"/>
			//if (!Directory.Exists(engine.GlobalProperties.SetProperty()))
			//{ }


            new MSBuildLog(engine);
            return engine;
        }
Beispiel #3
0
 public void TearDownAttribute()
 {
     engine.Shutdown();
     engineProxy = null;
     engineProxy2 = null;
     engine = null;
 }
Beispiel #4
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 void TestItems1 ()
		{
			Engine engine = new Engine (Consts.BinPath);
			Project proj = engine.CreateNewProject ();

			string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<ItemGroup>
						<Item0 Include='A' />
						<Item1 Include='A;B;C' />
						<Item2 Include='@(Item1);A;D' />
						<Item3 Include='@(Item2)' Exclude='A' />
						<Item4 Include='@(Item1);Q' Exclude='@(Item2)' />
						<Item5 Include='@(Item1)' Exclude='@(Item2)' />
						<Item6 Include='@(Item2)' Exclude='@(Item1)' />
						<Item7 Include='@(item_that_doesnt_exist)' />
					</ItemGroup>
				</Project>
			";

			proj.LoadXml (documentString);
			CheckItems (proj, "Item0", "A1", "A");
			CheckItems (proj, "Item1", "A2", "A", "B", "C");
			CheckItems (proj, "Item2", "A3", "A", "B", "C", "A", "D");
			CheckItems (proj, "Item3", "A4", "B", "C", "D");
			CheckItems (proj, "Item4", "A5", "Q");
			CheckItems (proj, "Item5", "A6");
			CheckItems (proj, "Item6", "A7", "D");
			CheckItems (proj, "Item7", "A8");
		}
        public void ExecutionProperties()
        {
            Engine engine = new Engine();
                   engine.BinPath="TestBinPath";

            ArrayList targetsToBuild = new ArrayList();
            targetsToBuild.Add("targetName");
            ProjectBuildState projectContext = new ProjectBuildState(new BuildRequest(-1, null, null, (BuildPropertyGroup)null, null, -1, false, false), targetsToBuild, new BuildEventContext(0, 1, 1, 1));

            TaskExecutionContext context = new TaskExecutionContext(null, null, null, projectContext, 4, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));

            Assert.IsTrue(context.BuildContext.TargetNamesToBuild.Contains("targetName"), "Expected target list to contain targetName");

            Assert.AreEqual(EngineCallback.inProcNode,context.NodeIndex);

            Assert.IsNull(context.ParentTarget,"Expected ParentTarget to be null");

            context.SetTaskOutputs(false, null, 0);

            Assert.IsFalse(context.TaskExecutedSuccessfully );
            Assert.IsNull(context.ThrownException, "Expected ThrownException to be null");

            context.SetTaskOutputs(true, new Exception(), 0);

            Assert.IsTrue(context.TaskExecutedSuccessfully);
            Assert.IsNotNull(context.ThrownException,"Expected ThrownException to not be null");


        }
Beispiel #7
0
		public void TestCondition1 ()
		{
			Engine engine = new Engine (Consts.BinPath);
			Project proj = engine.CreateNewProject ();

			string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<PropertyGroup>
						<A Condition='true'></A>
						<B Condition='false'></B>
						<C Condition='TRUE'></C>
						<D Condition='FALSE'></D>
						<E Condition=''>A</E>
					</PropertyGroup>
				</Project>
			";

			proj.LoadXml (documentString);

			Assert.IsNotNull (proj.EvaluatedProperties ["A"], "A1");
			Assert.IsNull (proj.EvaluatedProperties ["B"], "A2");
			Assert.IsNotNull (proj.EvaluatedProperties ["C"], "A3");
			Assert.IsNull (proj.EvaluatedProperties ["D"], "A4");
			Assert.IsNotNull (proj.EvaluatedProperties ["E"], "A5");
		}
 public void SetUp()
 {
     // Whole bunch of setup code.
     XmlElement taskNode = new XmlDocument().CreateElement("MockTask");
     LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));
     Engine engine = new Engine(@"c:\");
     loggingHelper = new EngineLoggingServicesHelper();
     engine.LoggingServices = loggingHelper;
     Project project = new Project(engine);
     taskExecutionModule = new MockTaskExecutionModule(new EngineCallback(engine));
     // Set up some "fake data" which will be passed to the Task Execution State object
     Hashtable[] fakeArray = new Hashtable[1];
     fakeArray[0] = new Hashtable();
     projectLevelProprtiesForInference = new BuildPropertyGroup();
     projectLevelPropertiesForExecution = new BuildPropertyGroup();
     inferenceBucketItemsByName = fakeArray;
     inferenceBucketMetaData = fakeArray;
     projectLevelItemsForInference = new Hashtable();
     executionBucketItemsByName = fakeArray;
     executionBucketMetaData = fakeArray;
     projectLevelItemsForExecution = new Hashtable();
     hostObject = null;
     projectFileOfTaskNode = "In Memory";
     parentProjectFullFileName = project.FullFileName;
     nodeProxyId = engine.EngineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
     executionDirectory = Directory.GetCurrentDirectory();
     projectId = project.Id;
 }
 public void Initialize()
 {
     engine = new Engine();
     myProject = new Project(engine);
     myLogger = new MockLogger();
     myProject.ParentEngine.RegisterLogger(myLogger);
 }
Beispiel #10
0
        /// <summary>
        /// Initialize the build engine. Sets the build enabled property to true. The engine is initialzed if the passed in engine is null or does not have its bin path set.
        /// </summary>
        /// <param name="engine">An instance of MSBuild.Engine build engine, that will be checked if initialized.</param>
        /// <param name="engine">The service provider.</param>
        /// <returns>The buildengine to use.</returns>
        internal static MSBuild.Engine InitializeMsBuildEngine(MSBuild.Engine existingEngine, IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentException("serviceProvider");
            }

#if VS2005
            if (existingEngine == null || existingEngine.BinPath == null)
            {
                MSBuild.Engine buildEngine = MSBuild.Engine.GlobalEngine;

                // We must set the MSBuild path prior to calling CreateNewProject on the msbuild project or we will fail
                buildEngine.BinPath = Utilities.GetMsBuildPath(serviceProvider);
                return(buildEngine);
            }
#else
            if (existingEngine == null)
            {
                MSBuild.Engine buildEngine = MSBuild.Engine.GlobalEngine;
                return(buildEngine);
            }
#endif

            return(existingEngine);
        }
Beispiel #11
0
 internal Introspector(Engine parentEngine, ProjectManager projectManager, NodeManager nodeManager)
 {
     this.parentEngine   = parentEngine;
     this.projectManager = projectManager;
     this.nodeManager    = nodeManager;
     this.ignoreTimeout  = 0;
 }
		public void TestProperties2 ()
		{
			Engine engine = new Engine (Consts.BinPath);
			Project proj = engine.CreateNewProject ();

			string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<UsingTask TaskName='StringTestTask' AssemblyFile='Test\resources\TestTasks.dll' />
					<PropertyGroup>
						<A>A</A>
						<B>B</B>
					</PropertyGroup>

					<Target Name='Main' >
						<StringTestTask Array='$(A)$(B)'>
							<Output TaskParameter='Array' ItemName='Out' />
						</StringTestTask>
					</Target>
				</Project>
			";

			proj.LoadXml (documentString);
			proj.Build ("Main");
			Assert.AreEqual (1, proj.GetEvaluatedItemsByName ("Out").Count, "A1");
			Assert.AreEqual ("AB", proj.GetEvaluatedItemsByName ("Out") [0].Include, "A2");
		}
Beispiel #13
0
		public void TestFromXml2 ()
		{
                        string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<Target Name='Target' Condition='false' DependsOnTargets='X' >
					</Target>
                                </Project>
                        ";

			engine = new Engine (Consts.BinPath);

                        project = engine.CreateNewProject ();
                        project.LoadXml (documentString);

			Target[] t = new Target [1];
			project.Targets.CopyTo (t, 0);

			Assert.AreEqual ("false", t [0].Condition, "A1");
			Assert.AreEqual ("X", t [0].DependsOnTargets, "A2");

			t [0].Condition = "true";
			t [0].DependsOnTargets = "A;B";

			Assert.AreEqual ("true", t [0].Condition, "A3");
			Assert.AreEqual ("A;B", t [0].DependsOnTargets, "A4");
		}
		public void TestAssemblyFile2 ()
		{
			string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<UsingTask
						AssemblyFile='Test/resources/TestTasks.dll'
						TaskName='SimpleTask'
					/>
				</Project>
			";

			engine = new Engine (Consts.BinPath);
			project = engine.CreateNewProject ();
			project.LoadXml (documentString);
			
			IEnumerator en = project.UsingTasks.GetEnumerator ();
			en.MoveNext ();
			
			UsingTask ut = (UsingTask) en.Current;
			
			Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1");
			Assert.IsNull (ut.AssemblyName, "A2");
			Assert.AreEqual (null, ut.Condition, "A3");
			Assert.AreEqual (false, ut.IsImported, "A4");
			Assert.AreEqual ("SimpleTask", ut.TaskName, "A5");
		}
        public void TestFalseWhen () {
            Engine engine;
            Project project;
            BuildItemGroup[] groups = new BuildItemGroup[1];

            string documentString = @"
				<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                    <Choose>
                        <When Condition=""'$(Configuration)' == 'False'"">
					        <ItemGroup>
						        <A Include='a' />
					        </ItemGroup>
                        </When>
                    </Choose>
				</Project>
			";

            engine = new Engine (Consts.BinPath);
            project = engine.CreateNewProject ();
            project.LoadXml (documentString);

            //Assert.AreEqual (1, project.ItemGroups.Count, "A1");
            Assert.AreEqual (0, project.PropertyGroups.Count, "A2");
            Assert.AreEqual (0, project.EvaluatedItems.Count, "A3");
            Assert.AreEqual (0, project.EvaluatedItemsIgnoringCondition.Count, "A4");
        }
Beispiel #16
0
        public static bool Build(Project pProj, OutputWindowPane pPane, string pTarget, NameValueCollection pParams)
        {
            Microsoft.Build.BuildEngine.Engine buildEngine = new Microsoft.Build.BuildEngine.Engine();
              BuildExecutor executor = new BuildExecutor(pPane);

              RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework", false);
              if (key == null) {
            throw new Exception("Failed to determine .NET Framework install root - no .NETFramework key");
              }
              string installRoot = key.GetValue("InstallRoot") as string;
              if (installRoot == null) {
            throw new Exception("Failed to determine .NET Framework install root - no InstallRoot value");
              }
              key.Close();

              buildEngine.BinPath = Path.Combine(installRoot, string.Format("v{0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build));
              buildEngine.RegisterLogger(executor);

              executor.Verbosity = LoggerVerbosity.Normal;

              BuildPropertyGroup properties = new BuildPropertyGroup();
              foreach (string propKey in pParams.Keys) {
            string val = pParams[propKey];

            properties.SetProperty(propKey, val, true);
              }

              return buildEngine.BuildProjectFile(pProj.FileName, new string[]{pTarget}, properties);
        }
		public ProjectBuilder (string file, string binDir)
		{
			this.file = file;
			engine = new Engine (binDir);
			engine.GlobalProperties.SetProperty ("BuildingInsideVisualStudio", "true");
			Refresh ();
		}
		public void Setup()
		{
			ccu = new CodeCompileUnit();
			mocks = new MockRepository();
			engine = Engine.GlobalEngine;
			engine.BinPath = @"C:\Program Files (x86)\MSBuild";
			project = new Project();
			buildEngine = mocks.DynamicMock<MockBuildEngine>(project);

			logger = new NullLogger();
			parserService = mocks.DynamicMock<ISiteTreeGeneratorService>();
			naming = mocks.DynamicMock<INamingService>();
			sourceStorage = mocks.DynamicMock<IParsedSourceStorageService>();
			source = mocks.DynamicMock<ISourceGenerator>();
			typeResolver = mocks.DynamicMock<ITypeResolver>();
			treeService = mocks.DynamicMock<ITreeCreationService>();
			viewSourceMapper = mocks.DynamicMock<IViewSourceMapper>();
			generator = mocks.DynamicMock<IGenerator>();

			task = new GenerateMonoRailSiteTreeTask(logger, parserService, naming, source, sourceStorage, typeResolver,
			                                         treeService, viewSourceMapper, generator);

			item = mocks.DynamicMock<ITaskItem>();
			parsedSource = mocks.DynamicMock<IParser>();
		}
Beispiel #19
0
        protected override bool CompileSingle(Engine engine, AbstractBaseGenerator gen, string workingPath, string target)
        {
            try
            {
                using (log4net.NDC.Push("Compiling " + gen.Description))
                {
                    Log.DebugFormat("Loading MsBuild Project");
                    var proj = new Project(engine);
                    proj.Load(Helper.PathCombine(workingPath, gen.TargetNameSpace, gen.ProjectFileName));

                    Log.DebugFormat("Compiling");
                    if (engine.BuildProject(proj, target))
                    {
                        return true;
                    }
                    else
                    {
                        Log.ErrorFormat("Failed to compile {0}", gen.Description);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Failed compiling " + gen.Description, ex);
                return false;
            }
        }
		public void TestExecution1 ()
		{
			Engine engine;
			Project project;

			string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<Target Name='1'>
						<GetFrameworkPath>
							<Output
								TaskParameter='Path'
								PropertyName='Path'
							/>
						</GetFrameworkPath>
					</Target>
				</Project>
			";

			engine = new Engine (Consts.BinPath);
			project = engine.CreateNewProject ();
			project.LoadXml (documentString);
			Assert.IsTrue (project.Build ("1"), "A1");

			Assert.IsNotNull (project.EvaluatedProperties ["Path"], "A2");
			Assert.IsTrue (String.Empty != project.EvaluatedProperties ["Path"].FinalValue, "A3");
		}
        public void Initialize()
        {
            ObjectModelHelpers.DeleteTempProjectDirectory();

            engine = new Engine();
            project = new Project(engine);
        }
Beispiel #22
0
		internal Target (XmlElement targetElement, Project project, ImportedProject importedProject)
		{
			if (project == null)
				throw new ArgumentNullException ("project");
			if (targetElement == null)
				throw new ArgumentNullException ("targetElement");

			this.targetElement = targetElement;
			this.name = targetElement.GetAttribute ("Name");

			this.project = project;
			this.engine = project.ParentEngine;
			this.importedProject = importedProject;

			this.onErrorElements  = new List <XmlElement> ();
			this.buildState = BuildState.NotStarted;
			this.buildTasks = new List <BuildTask> ();
			this.batchingImpl = new TargetBatchingImpl (project, this.targetElement);

			bool onErrorFound = false;
			foreach (XmlNode xn in targetElement.ChildNodes) {
				if (xn is XmlElement) {
					XmlElement xe = (XmlElement) xn;
					if (xe.Name == "OnError") {
						onErrorElements.Add (xe);
						onErrorFound = true;
					} else if (onErrorFound)
						throw new InvalidProjectFileException (
							"The element <OnError> must be last under element <Target>. Found element <Error> instead.");
					else
						buildTasks.Add (new BuildTask (xe, this));
				}
			}
		}
		void MsVisitProjects(VisitProject visitor)
		{
			Engine e = new Engine(RuntimeEnvironment.GetRuntimeDirectory());
            if(e.GetType().Assembly.GetName().Version.Major == 2)
				try { e.GlobalProperties.SetProperty("MSBuildToolsPath", RuntimeEnvironment.GetRuntimeDirectory()); }
				catch { }

			foreach (FileInfo file in _projects)
			{
				Project prj = new Project(e);
				try
				{
					prj.Load(file.FullName);
				}
				catch (Exception ex)
				{
					Console.Error.WriteLine("Unable to open project: {0}", file);
					Log.Verbose(ex.ToString());
					continue;
				}

				visitor(new MsBuildProject(prj));
				e.UnloadProject(prj);
			}
		}
Beispiel #24
0
        public void ConstructorEngineNoParameters()
        {
            Engine e = new Engine();

            string binPath20 = GetBinPathFromRegistry("2.0");

            if (binPath20 == null)
            {
                // if 2.0 can't be found in the registry, it's still the default, 
                // but we need to get it another way.
                binPath20 = FrameworkLocationHelper.PathToDotNetFrameworkV20;
            }

            if (binPath20 != null)
            {
                Assertion.AssertEquals("2.0", e.DefaultToolsVersion);
                Assertion.AssertEquals(binPath20, e.BinPath);
            }
            else
            {
                Assertion.AssertEquals("4.0", e.DefaultToolsVersion);
                Assertion.AssertEquals(GetBinPathFromRegistry("4.0"), e.BinPath);
            }

            Assertion.AssertEquals(true, e.BuildEnabled);
            Assertion.AssertEquals(false, e.IsBuilding);
            Assertion.AssertEquals(false, e.OnlyLogCriticalEvents);
        }
		public void TestGetEnumerator ()
		{
			string documentString = @"
				<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<UsingTask
						AssemblyFile='Test/resources/TestTasks.dll'
						TaskName='TrueTestTask'
					/>
					<UsingTask
						AssemblyFile='Test/resources/TestTasks.dll'
						TaskName='FalseTestTask'
					/>
				</Project>
			";

			engine = new Engine (Consts.BinPath);
			project = engine.CreateNewProject ();
			project.LoadXml (documentString);
			
			IEnumerator en = project.UsingTasks.GetEnumerator ();
			en.MoveNext ();

			Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A1");
			Assert.AreEqual ("TrueTestTask", ((UsingTask) en.Current).TaskName, "A2");

			en.MoveNext ();

			Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A3");
			Assert.AreEqual ("FalseTestTask", ((UsingTask) en.Current).TaskName, "A4");

			Assert.IsFalse (en.MoveNext ());
		}
Beispiel #26
0
 internal override void Execute(Engine parentEngine)
 {
     NodeStatus nodeStatus = parentEngine.RequestStatus(requestId);
     ErrorUtilities.VerifyThrow(parentEngine.Router.ParentNode != null,
                                "Method should be called only on child nodes");
     parentEngine.Router.ParentNode.PostStatus(nodeStatus, false /* don't block waiting on the send */);
 }
		public void TestExecution1 ()
		{
			Engine engine;
			Project project;

			string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
					<ItemGroup>
						<Dir Include='b' />
						<Dir Include='c' />
						<Dir Include='d\e' />
					</ItemGroup>
					<Target Name='1'>
						<CombinePath BasePath='a' Paths='@(Dir)'>
							<Output
								TaskParameter='CombinedPaths'
								ItemName='Out'
							/>
						</CombinePath>
					</Target>
				</Project>
			";

			engine = new Engine (Consts.BinPath);
			project = engine.CreateNewProject ();
			project.LoadXml (documentString);
			Assert.IsTrue (project.Build ("1"), "A1");

			BuildItemGroup output = project.GetEvaluatedItemsByName ("Out");
			Assert.AreEqual (3, output.Count, "A2");
			Assert.AreEqual (Path.Combine ("a", "b"), output [0].FinalItemSpec, "A3");
			Assert.AreEqual (Path.Combine ("a", "c"), output [1].FinalItemSpec, "A4");
			Assert.AreEqual (Path.Combine ("a", Path.Combine ("d", "e")), output [2].FinalItemSpec, "A5");

		}
Beispiel #28
0
        public void SimpleAddAndRetrieveProject()
        {
            // Initialize engine.
            Engine engine = new Engine(@"c:\");

            // Instantiate new project manager.
            ProjectManager projectManager = new ProjectManager();

            // Set up variables that represent the information we would be getting from 
            // the "MSBuild" task.
            string fullPath = @"c:\rajeev\temp\myapp.proj";
            BuildPropertyGroup globalProperties = new BuildPropertyGroup();
            globalProperties.SetProperty("Configuration", "Debug");

            // Create a new project that matches the information that we're pretending
            // to receive from the MSBuild task.
            Project project1 = new Project(engine);
            project1.FullFileName = fullPath;
            project1.GlobalProperties = globalProperties;

            // Add the new project to the ProjectManager.
            projectManager.AddProject(project1);

            // Try and retrieve the project from the ProjectManager based on the fullpath + globalprops,
            // and make sure we get back the same project we added.
            Assertion.AssertEquals(project1, projectManager.GetProject(fullPath, globalProperties, null));
        }
Beispiel #29
0
		public ProjectBuilder (BuildEngine buildEngine, Engine engine, string file)
		{
			this.file = file;
			this.engine = engine;
			this.buildEngine = buildEngine;
			consoleLogger = new MDConsoleLogger (LoggerVerbosity.Normal, LogWriteLine, null, null);
		}
		public void Test1 ()
		{
			string documentString = @"
                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion='3.5'>
				
				<ItemGroup>
					<Items Include='A'>
						<MD>Value1</MD>
					</Items>
					<Items Include='A'>
						<MD>Value1</MD>
					</Items>

					<Items Include='A'>
						<MD>Value2</MD>
						<MD2>Value2</MD2>
					</Items>

					<Items Include='B'>
						<MD>Value1</MD>
					</Items>
					<Items Include='B'>
						<MD>Value1</MD>
					</Items>
					<Items Include='C'>
						<MD>Value1</MD>
					</Items>
					<Items Include='A'>
						<MD>Value3</MD>
						<MD3>Value3</MD3>
					</Items>
				</ItemGroup>

					<Target Name='Main'>
						<RemoveDuplicates Inputs='@(Items)'>
							<Output TaskParameter='Filtered' ItemName='Filtered'/>
						</RemoveDuplicates>
						<Message Text=""Filtered items: %(Filtered.Identity) MD: %(Filtered.MD) MD2: %(Filtered.MD2) MD3: %(Filtered.MD3)""/>
					</Target>
				</Project>
			";

			Engine engine = new Engine (Consts.BinPath);

			TestMessageLogger testLogger = new TestMessageLogger ();
			engine.RegisterLogger (testLogger);

			Project project = engine.CreateNewProject ();
			project.LoadXml (documentString);
			if (!project.Build ("Main")) {
				testLogger.DumpMessages ();
				Assert.Fail ("Build failed");
			}

			testLogger.CheckLoggedMessageHead ("Filtered items: A MD: Value1 MD2:  MD3: ", "A1");
			testLogger.CheckLoggedMessageHead ("Filtered items: B MD: Value1 MD2:  MD3: ", "A2");
			testLogger.CheckLoggedMessageHead ("Filtered items: C MD: Value1 MD2:  MD3: ", "A3");
			Assert.AreEqual (0, testLogger.NormalMessageCount, "Unexpected extra messages found");
		}
Beispiel #31
0
        public void TestMSBuildForwardPropertiesFromChild()
        {
            Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", null);
            Engine childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
            string[] propertiesToSerialize = childEngine.PropertyListToSerialize;
            Assert.IsNull(propertiesToSerialize, "Expected propertiesToSerialize to be null");
	    childEngine.Shutdown();
            
	    Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", string.Empty);
            childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
            propertiesToSerialize = childEngine.PropertyListToSerialize;
            Assert.IsNull(propertiesToSerialize, "Expected propertiesToSerialize to be null");
            childEngine.Shutdown();

             Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;Configuration");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(string.Compare(propertiesToSerialize[1], "Configuration") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 2);
             childEngine.Shutdown();

             Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;;;;;;;;;;Configuration");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(string.Compare(propertiesToSerialize[1], "Configuration") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 2);
             childEngine.Shutdown();

             Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 1);
             childEngine.Shutdown();

             Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 1);
             childEngine.Shutdown();
             
            Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", ";Platform");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 1);
             childEngine.Shutdown();


             Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", ";Platform;");
             childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
             propertiesToSerialize = childEngine.PropertyListToSerialize;
             Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
             Assert.IsTrue(propertiesToSerialize.Length == 1);
             childEngine.Shutdown();
        }
Beispiel #32
0
        protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package)
        {
            this.package = package;
            this.site    = package;

            // Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters.
            this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site);
        }
Beispiel #33
0
        internal static void EnsureCorrectTempProject(MSBuild.Project baseProject,
                                                      string configuration, string platform,
                                                      ref MSBuild.Project tempProject)
        {
            if (configuration == null && platform == null)
            {
                // unload temp project
                if (tempProject != null && tempProject != baseProject)
                {
                    tempProject.ParentEngine.UnloadAllProjects();
                }
                tempProject = null;
                return;
            }
            if (configuration == null)
            {
                configuration = baseProject.GetEvaluatedProperty("Configuration");
            }
            if (platform == null)
            {
                platform = baseProject.GetEvaluatedProperty("Platform");
            }

            if (tempProject != null &&
                tempProject.GetEvaluatedProperty("Configuration") == configuration &&
                tempProject.GetEvaluatedProperty("Platform") == platform)
            {
                // already correct
                return;
            }
            if (baseProject.GetEvaluatedProperty("Configuration") == configuration &&
                baseProject.GetEvaluatedProperty("Platform") == platform)
            {
                tempProject = baseProject;
                return;
            }
            // create new project

            // unload old temp project
            if (tempProject != null && tempProject != baseProject)
            {
                tempProject.ParentEngine.UnloadAllProjects();
            }
            try {
                MSBuild.Engine engine = CreateEngine();
                tempProject = engine.CreateNewProject();
                // tell MSBuild the path so that projects containing <Import Project="relativePath" />
                // can be loaded
                tempProject.FullFileName = baseProject.FullFileName;
                MSBuildBasedProject.InitializeMSBuildProject(tempProject);
                tempProject.LoadXml(baseProject.Xml);
                tempProject.SetProperty("Configuration", configuration);
                tempProject.SetProperty("Platform", platform);
            } catch (Exception ex) {
                ICSharpCode.Core.MessageService.ShowWarning(ex.ToString());
                tempProject = baseProject;
            }
        }
Beispiel #34
0
        /// <summary>
        /// Loads a project file for the file. If the build project exists and it was loaded with a different file then it is unloaded first.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <param name="exitingBuildProject">An Existing build project that will be reloaded.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project ReinitializeMsBuildProject(MSBuild.Engine buildEngine, string fullProjectPath, MSBuild.Project exitingBuildProject)
        {
            // If we have a build project that has been loaded with another file unload it.
            if (exitingBuildProject != null && !NativeMethods.IsSamePath(exitingBuildProject.FullFileName, fullProjectPath))
            {
                exitingBuildProject.ParentEngine.UnloadProject(exitingBuildProject);
            }

            return(Utilities.InitializeMsBuildProject(buildEngine, fullProjectPath));
        }
Beispiel #35
0
        /// <summary>
        /// Initialize the build engine. Sets the build enabled property to true. The engine is initialzed if the passed in engine is null or does not have its bin path set.
        /// </summary>
        /// <param name="engine">An instance of MSBuild.Engine build engine, that will be checked if initialized.</param>
        /// <param name="engine">The service provider.</param>
        /// <returns>The buildengine to use.</returns>
        internal static MSBuild.Engine InitializeMsBuildEngine(MSBuild.Engine existingEngine, IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            if (existingEngine == null)
            {
                MSBuild.Engine buildEngine = MSBuild.Engine.GlobalEngine;
                return(buildEngine);
            }

            return(existingEngine);
        }
Beispiel #36
0
        /// <summary>
        /// Loads a project file for the file. If the build project exists and it was loaded with a different file then it is unloaded first.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <param name="exitingBuildProject">An Existing build project that will be reloaded.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project ReinitializeMsBuildProject(MSBuild.Engine buildEngine, string fullProjectPath, MSBuild.Project exitingBuildProject)
        {
            // If we have a build project that has been loaded with another file unload it.
            try
            {
                if (exitingBuildProject != null && exitingBuildProject.ParentEngine != null && !NativeMethods.IsSamePath(exitingBuildProject.FullFileName, fullProjectPath))
                {
                    exitingBuildProject.ParentEngine.UnloadProject(exitingBuildProject);
                }
            }
            // We  catch Invalid operation exception because if the project was unloaded while we touch the ParentEngine the msbuild API throws.
            // Is there a way to figure out that a project was unloaded?
            catch (InvalidOperationException)
            {
            }

            return(Utilities.InitializeMsBuildProject(buildEngine, fullProjectPath));
        }
Beispiel #37
0
        /// <summary>
        /// Initializes the in memory project. Sets BuildEnabled on the project to true.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project InitializeMsBuildProject(MSBuild.Engine buildEngine, string fullProjectPath)
        {
            if (buildEngine == null)
            {
                throw new ArgumentNullException("engine");
            }

            if (String.IsNullOrEmpty(fullProjectPath))
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fullProjectPath");
            }

            // Check if the project already has been loaded with the fullProjectPath. If yes return the build project associated to it.
            MSBuild.Project buildProject = buildEngine.GetLoadedProject(fullProjectPath);

            if (buildProject == null)
            {
                buildProject = buildEngine.CreateNewProject();
                buildProject.BuildEnabled = true;
                buildProject.Load(fullProjectPath);
            }

            return(buildProject);
        }
Beispiel #38
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
        }