Пример #1
0
        /// <summary>
        /// This method generates an XmlDocument representing an MSBuild project wrapper for a VC project
        /// </summary>
        /// <owner>LukaszG</owner>
        static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion)
        {
            string  projectPath    = Path.GetFullPath(vcProjectFilename);
            Project msbuildProject = null;

            try
            {
                msbuildProject = new Project(parentEngine, toolsVersion);
            }
            catch (InvalidOperationException)
            {
                BuildEventFileInfo fileInfo = new BuildEventFileInfo(projectPath);
                string             errorCode;
                string             helpKeyword;
                string             message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", toolsVersion);
                throw new InvalidProjectFileException(projectPath, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword);
            }

            msbuildProject.IsLoadedByHost = false;
            msbuildProject.DefaultTargets = "Build";

            string wrapperProjectToolsVersion = SolutionWrapperProject.DetermineWrapperProjectToolsVersion(toolsVersion);

            msbuildProject.DefaultToolsVersion = wrapperProjectToolsVersion;

            BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);

            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' == '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)");

            propertyGroup           = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)|$(Platform)");

            // only use PlatformName if we only have the platform part
            propertyGroup           = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' == '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("PlatformName", "$(Platform)");

            AddVCBuildTarget(msbuildProject, projectPath, "Build", null);
            AddVCBuildTarget(msbuildProject, projectPath, "Clean", "Clean");
            AddVCBuildTarget(msbuildProject, projectPath, "Rebuild", "Rebuild");
            AddVCBuildTarget(msbuildProject, projectPath, "Publish", "Publish");

            // Special environment variable to allow people to see the in-memory MSBuild project generated
            // to represent the VC project.
            if (Environment.GetEnvironmentVariable("MSBuildEmitSolution") != null)
            {
                msbuildProject.Save(vcProjectFilename + ".proj");
            }

            return(msbuildProject.XmlDocument);
        }
Пример #2
0
        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;
        }
Пример #3
0
        /// <summary>
        /// Evaluates the specified condition in the project.
        /// WARNING: EvaluateCondition might add a temporary property group and remove it again,
        /// which invalidates enumerators over the list of property groups!
        /// </summary>
        internal static bool EvaluateCondition(MSBuild.Project project,
                                               string condition)
        {
            const string propertyName = "MSBuildInternalsEvaluateConditionDummyPropertyName";

            MSBuild.BuildPropertyGroup pGroup = project.AddNewPropertyGroup(true);
            pGroup.AddNewProperty(propertyName, "ConditionFalse");
            pGroup.AddNewProperty(propertyName, "ConditionTrue").Condition = condition;
            bool result = project.GetEvaluatedProperty(propertyName) == "ConditionTrue";

            project.RemovePropertyGroup(pGroup);
            return(result);
        }
        public override bool Execute()
        {
            string metaprojFile = _source.ToString();
            // Check the metaproj file exists
            // otherwise warn it has to be emitted thanks to 'set MSBuildEmitSolution=1'

            if (!File.Exists(metaprojFile))
            {
                Log.LogWarning("The metaproj file " +
                                metaprojFile + " does not exist. You can emit it"
                                + " by setting MSBuildEmitSolution to 1 while"
                                + " calling MsBuild.");
            }
            else
            {
                try
                {
                    // Load metaproj file
                    XDocument metaproj = XDocument.Load(metaprojFile);
                    XNamespace xmlns = metaproj.Root.Attribute("xmlns").Value;

                    // Parse metaproj file
                    var currentSolutionConfigurationContents = "CurrentSolutionConfigurationContents";
                    var currentSolutionConfigurationContentsElements = metaproj.Root.Descendants(xmlns
                        + currentSolutionConfigurationContents);

                    if (currentSolutionConfigurationContentsElements.Count() == 0)
                        throw new Exception();

                    var solutionConfiguration =
                        currentSolutionConfigurationContentsElements.First().FirstNode;

                    if (solutionConfiguration == null)
                        throw new Exception();

                    _currentSolutionConfigurationContents =
                        solutionConfiguration.ToString(SaveOptions.OmitDuplicateNamespaces);

                    if (_save)
                    {
                        Project project = new Project();
                        project.DefaultToolsVersion = "4.0";

                        var propertyGroup = project.AddNewPropertyGroup(false);
                        propertyGroup.AddNewProperty(currentSolutionConfigurationContents,
                            _currentSolutionConfigurationContents);

                        project.Save(metaprojFile + ".filtered", System.Text.Encoding.UTF8);
                    }

                }
                catch (Exception ex)
                {
                    Log.LogError("Error trying to load metaproj file " +
                                    metaprojFile + ". " + ex.Message);
                }
            }

            // Log.HasLoggedErrors is true if the task logged any errors -- even
            // if they were logged from a task's constructor or property setter.
            // As long as this task is written to always log an error when it
            // fails, we can reliably return HasLoggedErrors.
            return !Log.HasLoggedErrors;
        }
Пример #5
0
 public void RemovePropertyGroup()
 {
     string mainProjFilename = String.Empty;
     try
     {
         mainProjFilename = ObjectModelHelpers.CreateTempFileOnDisk(TestData.PropertyGroup);
         Project mainProject = new Project(new Engine());
         BuildPropertyGroup groupToRemove = mainProject.AddNewPropertyGroup(true);
         Assertion.AssertEquals(1, mainProject.PropertyGroups.Count);
         mainProject.RemovePropertyGroup(groupToRemove);
         Assertion.AssertEquals(0, mainProject.PropertyGroups.Count);
     }
     finally
     {
         CompatibilityTestHelpers.RemoveFile(mainProjFilename);
     }
 }
Пример #6
0
        /// <summary>
        /// Adds solution related build event macros and other global properties to the wrapper project
        /// </summary>
        /// <param name="msbuildProject"></param>
        /// <param name="solution"></param>
        /// <owner>LukaszG</owner>
        static private void AddGlobalProperties(Project msbuildProject, SolutionParser solution)
        {
            BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);

            string directoryName = solution.SolutionFileDirectory;
            if (!directoryName.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                directoryName += Path.DirectorySeparatorChar;
            }

            propertyGroup.AddNewProperty("SolutionDir", directoryName, true /* treat as literal */);
            propertyGroup.AddNewProperty("SolutionExt", Path.GetExtension(solution.SolutionFile), true /* treat as literal */);
            propertyGroup.AddNewProperty("SolutionFileName", Path.GetFileName(solution.SolutionFile), true /* treat as literal */);
            propertyGroup.AddNewProperty("SolutionName", Path.GetFileNameWithoutExtension(solution.SolutionFile), true /* treat as literal */);

            propertyGroup.AddNewProperty("SolutionPath", Path.Combine(solution.SolutionFileDirectory, Path.GetFileName(solution.SolutionFile)), true /* treat as literal */);

            // Add other global properties
            BuildPropertyGroup propertyGroup2 = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);

            // Set the property "TargetFrameworkVersion". This is needed for the GetFrameworkPath target.
            // If TargetFrameworkVersion is already set by the user, use that value.
            // Otherwise if MSBuildToolsVersion is 2.0, use "v2.0"
            // Otherwise if MSBuildToolsVersion is 3.5, use "v3.5"
            // Otherwise use "v4.0".
            BuildProperty v20Property = propertyGroup2.AddNewProperty("TargetFrameworkVersion", "v2.0", true /* treat as literal */);
            BuildProperty v35Property = propertyGroup2.AddNewProperty("TargetFrameworkVersion", "v3.5", true /* treat as literal */);
            BuildProperty v40Property = propertyGroup2.AddNewProperty("TargetFrameworkVersion", "v4.0", true /* treat as literal */);
            v20Property.Condition = "'$(TargetFrameworkVersion)' == '' and '$(MSBuildToolsVersion)' == '2.0'";
            v35Property.Condition = "'$(TargetFrameworkVersion)' == '' and ('$(MSBuildToolsVersion)' == '3.5' or '$(MSBuildToolsVersion)' == '3.0')";
            v40Property.Condition = "'$(TargetFrameworkVersion)' == '' and '$(MSBuildToolsVersion)' == '4.0'";
        }
Пример #7
0
        /// <summary>
        /// Adds a new property group with contents of the given solution configuration to the project
        /// Internal for unit-testing.
        /// </summary>
        /// <param name="msbuildProject"></param>
        /// <param name="solution"></param>
        /// <param name="solutionConfiguration"></param>
        /// <owner>LukaszG</owner>
        static internal void AddPropertyGroupForSolutionConfiguration
        (
            Project msbuildProject, 
            SolutionParser solution,
            ConfigurationInSolution solutionConfiguration
        )
        {
            BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = GetConditionStringForConfiguration(solutionConfiguration);

            StringBuilder solutionConfigurationContents = new StringBuilder("<SolutionConfiguration>");

            // add a project configuration entry for each project in the solution
            foreach (ProjectInSolution project in solution.ProjectsInOrder)
            {
                ProjectConfigurationInSolution projectConfiguration = null;

                if (project.ProjectConfigurations.TryGetValue(solutionConfiguration.FullName, out projectConfiguration))
                {
                    solutionConfigurationContents.AppendFormat(
                        CultureInfo.InvariantCulture,
                        "<ProjectConfiguration Project=\"{0}\">{1}</ProjectConfiguration>",
                        project.ProjectGuid,
                        projectConfiguration.FullName
                    );
                }
            }

            solutionConfigurationContents.Append("</SolutionConfiguration>");

            propertyGroup.AddNewProperty("CurrentSolutionConfigurationContents", solutionConfigurationContents.ToString(), true /* treat as literal */);
        }
Пример #8
0
        /// <summary>
        /// Add a PropertyGroup to the project for a particular Asp.Net configuration.  This PropertyGroup
        /// will have the correct values for all the Asp.Net properties for this project and this configuration.
        /// </summary>
        /// <param name="msbuildProject"></param>
        /// <param name="proj"></param>
        /// <param name="configurationName"></param>
        /// <param name="aspNetCompilerParameters"></param>
        /// <param name="solutionFile"></param>
        /// <owner>RGoel</owner>
        static private void AddPropertyGroupForAspNetConfiguration
            (
            Project msbuildProject, 
            ProjectInSolution proj, 
            string configurationName, 
            AspNetCompilerParameters aspNetCompilerParameters,
            string solutionFile
            )
        {
            // Add a new PropertyGroup that is condition'd on the Configuration.
            BuildPropertyGroup newPropertyGroup = msbuildProject.AddNewPropertyGroup(false /* insertAtEndOfProject = false */);
            newPropertyGroup.Condition = String.Format(CultureInfo.InvariantCulture, " '$(AspNetConfiguration)' == '{0}' ", 
                EscapingUtilities.Escape(configurationName));

            // Add properties into the property group for each of the AspNetCompiler properties.
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetVirtualPath"), aspNetCompilerParameters.aspNetVirtualPath, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetPhysicalPath"), aspNetCompilerParameters.aspNetPhysicalPath, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetTargetPath"), aspNetCompilerParameters.aspNetTargetPath, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetForce"), aspNetCompilerParameters.aspNetForce, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetUpdateable"), aspNetCompilerParameters.aspNetUpdateable, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetDebug"), aspNetCompilerParameters.aspNetDebug, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetKeyFile"), aspNetCompilerParameters.aspNetKeyFile, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetKeyContainer"), aspNetCompilerParameters.aspNetKeyContainer, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetDelaySign"), aspNetCompilerParameters.aspNetDelaySign, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetAPTCA"), aspNetCompilerParameters.aspNetAPTCA, true);
            newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetFixedNames"), aspNetCompilerParameters.aspNetFixedNames, true);

            string aspNetPhysicalPath = aspNetCompilerParameters.aspNetPhysicalPath;
            if (!String.IsNullOrEmpty(aspNetPhysicalPath))
            {
                // Trim the trailing slash if one exists.
                if (
                        (aspNetPhysicalPath[aspNetPhysicalPath.Length - 1] == Path.AltDirectorySeparatorChar) ||
                        (aspNetPhysicalPath[aspNetPhysicalPath.Length - 1] == Path.DirectorySeparatorChar)
                    )
                {
                    aspNetPhysicalPath = aspNetPhysicalPath.Substring(0, aspNetPhysicalPath.Length - 1);
                }

                // This gets us the last folder in the physical path.
                string lastFolderInPhysicalPath = null;

                try
                {
                    lastFolderInPhysicalPath = Path.GetFileName(aspNetPhysicalPath);
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.NotExpectedException(e))
                        throw;

                    ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false,
                        "SubCategoryForSolutionParsingErrors",
                        new BuildEventFileInfo(solutionFile),
                        "SolutionParseInvalidProjectFileName",
                        proj.RelativePath, e.Message);
                }

                if (!String.IsNullOrEmpty(lastFolderInPhysicalPath))
                {
                    // If there is a global property called "OutDir" set, that means the caller is trying to 
                    // override the AspNetTargetPath.  What we want to do in this case is concatenate:
                    //  $(OutDir) + "\_PublishedWebsites" + (the last portion of the folder in the AspNetPhysicalPath).
                    BuildProperty targetPathOverrideProperty = newPropertyGroup.AddNewProperty(GenerateSafePropertyName(proj, "AspNetTargetPath"),
                        @"$(OutDir)" + 
                        EscapingUtilities.Escape(webProjectOverrideFolder) + Path.DirectorySeparatorChar + 
                        EscapingUtilities.Escape(lastFolderInPhysicalPath) + Path.DirectorySeparatorChar);
                    targetPathOverrideProperty.Condition = " '$(OutDir)' != '' ";
                }
            }
        }
Пример #9
0
        /// <summary>
        /// This method generates an XmlDocument representing an MSBuild project wrapper for a VC project
        /// </summary>
        /// <owner>LukaszG</owner>
        static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion)
        {
            string projectPath = Path.GetFullPath(vcProjectFilename);
            Project msbuildProject = null;

            try
            {
                msbuildProject = new Project(parentEngine, toolsVersion);
            }
            catch (InvalidOperationException)
            {
                BuildEventFileInfo fileInfo = new BuildEventFileInfo(projectPath);
                string errorCode;
                string helpKeyword;
                string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", toolsVersion);
                throw new InvalidProjectFileException(projectPath, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword);
            }

            msbuildProject.IsLoadedByHost = false;
            msbuildProject.DefaultTargets = "Build";

            string wrapperProjectToolsVersion = SolutionWrapperProject.DetermineWrapperProjectToolsVersion(toolsVersion);
            msbuildProject.DefaultToolsVersion = wrapperProjectToolsVersion;

            BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' == '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)");

            propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)|$(Platform)");

            // only use PlatformName if we only have the platform part
            propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' == '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("PlatformName", "$(Platform)");

            AddVCBuildTarget(msbuildProject, projectPath, "Build", null);
            AddVCBuildTarget(msbuildProject, projectPath, "Clean", "Clean");
            AddVCBuildTarget(msbuildProject, projectPath, "Rebuild", "Rebuild");
            AddVCBuildTarget(msbuildProject, projectPath, "Publish", "Publish");

            // Special environment variable to allow people to see the in-memory MSBuild project generated
            // to represent the VC project.
            if (Environment.GetEnvironmentVariable("MSBuildEmitSolution") != null)
            {
                msbuildProject.Save(vcProjectFilename + ".proj");
            }

            return msbuildProject.XmlDocument;
        }
Пример #10
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
        }
Пример #11
0
 public void PropertyGroupsGet()
 {
     Project p = new Project();
     p.LoadXml(TestData.PropertyGroup);
     p.SetProperty("n", "v");
     p.AddNewPropertyGroup(false);
     BuildPropertyGroupCollection buildPropertyGroups = p.PropertyGroups;
     Assertion.AssertEquals(3, buildPropertyGroups.Count);
     Assertion.AssertEquals(true, buildPropertyGroups.Equals(p.PropertyGroups));
 }
Пример #12
0
            public void AddNewPropertyGroupNotAFter()
            {
                Project p = new Project();
                p.AddNewImport("p", "c");
                BuildPropertyGroup buildPropertyGroup1 = p.AddNewPropertyGroup(false);

                Assertion.AssertEquals(true, p.Xml.IndexOf("<PropertyGroup />") < p.Xml.IndexOf("<Import Condition=\"c\" Project=\"p\" />"));
            }
Пример #13
0
 public void AddNewPropertyGroupAfter()
 {
     Project p = new Project();
     BuildPropertyGroup buildPropertyGroup1 = p.AddNewPropertyGroup(false);
     buildPropertyGroup1.Condition = "true";
     BuildPropertyGroup buildPropertyGroup2 = p.AddNewPropertyGroup(true);
     buildPropertyGroup2.Condition = "false";
     Assertion.AssertEquals(true, p.Xml.IndexOf("<PropertyGroup Condition=\"true\" />") < p.Xml.IndexOf("<PropertyGroup Condition=\"false\" />"));
     Assertion.AssertEquals(2, p.PropertyGroups.Count);
     Assertion.AssertEquals(true, p.IsDirty);
 }
Пример #14
0
 public void AddNewPropertyGroupBeforeOneOtherPropertyGroupAndAUsingTask()
 {
     Project p = new Project();
     BuildPropertyGroup buildPropertyGroup1 = p.AddNewPropertyGroup(true);
     buildPropertyGroup1.Condition = "true";
     p.AddNewImport("p", "c");
     BuildPropertyGroup buildPropertyGroup2 = p.AddNewPropertyGroup(false);
     buildPropertyGroup2.Condition = "false";
     Assertion.AssertEquals(true, p.Xml.IndexOf("<PropertyGroup Condition=\"true\" />") < p.Xml.IndexOf("<PropertyGroup Condition=\"false\" />"));
     Assertion.AssertEquals(true, p.Xml.IndexOf("<PropertyGroup Condition=\"true\" />") < p.Xml.IndexOf("<Import Condition=\"c\" Project=\"p\" />"));
     Assertion.AssertEquals(2, p.PropertyGroups.Count);
 }
Пример #15
0
 public void AddNewPropertyGroup()
 {
     Project p = new Project();
     BuildPropertyGroup buildPropertyGroup = p.AddNewPropertyGroup(true);
     buildPropertyGroup.AddNewProperty("n", "v");
     buildPropertyGroup.Condition = "true";
     Assertion.AssertEquals(true, p.Xml.Contains("<PropertyGroup Condition=\"true\">"));
     Assertion.AssertEquals(1, p.PropertyGroups.Count);
     Assertion.AssertEquals(true, p.IsDirty);
 }
Пример #16
0
 public void RemovePropertyGroupsWithMatchingConditionMatchInImported_True()
 {
     string importedProjFilename = String.Empty;
     string mainProjFilename = String.Empty;
     try
     {
         importedProjFilename = ObjectModelHelpers.CreateTempFileOnDisk(TestData.PropertyGroup);
         mainProjFilename = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
         Project mainProject = new Project(new Engine());
         Project importedProject = new Project(mainProject.ParentEngine);
         mainProject.Load(mainProjFilename);
         importedProject.Load(importedProjFilename);
         BuildPropertyGroup referenceGroup = mainProject.AddNewPropertyGroup(true);
         referenceGroup.Condition = "true";
         mainProject.SetImportedProperty("newp", "newv", "true", importedProject);
         Assertion.AssertEquals(2, mainProject.PropertyGroups.Count);
         mainProject.RemovePropertyGroupsWithMatchingCondition("true", true);
         Assertion.AssertEquals(0, mainProject.PropertyGroups.Count);
     }
     finally
     {
         CompatibilityTestHelpers.RemoveFile(importedProjFilename);
         CompatibilityTestHelpers.RemoveFile(mainProjFilename);
     }
 }
Пример #17
0
        public void S3ExistsPrefixProjectFile()
        {
            if (!IsEmpty)
            {
                string prefix = Guid.NewGuid().ToString();
                string key = prefix + "/jquery.min.js";

                Project project = new Project(Engine.GlobalEngine);
                project.Load("S3Exists.proj");

                BuildPropertyGroup properties = project.AddNewPropertyGroup(false);
                properties.AddNewProperty("Prefix", prefix);
                properties.AddNewProperty("S3AccessKeyId", AccessKeyId);
                properties.AddNewProperty("S3BucketName", BucketName);
                properties.AddNewProperty("S3SecretAccessKeyId", SecretAccessKeyId);
                properties.AddNewProperty("S3UseSsl", UseSsl.ToString());

                project.Build("PrefixExists");

                PutObjectRequest request = new PutObjectRequest()
                    .WithBucketName(BucketName)
                    .WithKey(key)
                    .WithFilePath(@"script\jquery.min.js");

                using (PutObjectResponse response = Client.PutObject(request))
                {
                    cleanupKeys.Add(key);
                }

                project.Build("PrefixExists");
            }
        }
        /// <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);
            }
        }
Пример #19
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

        }
Пример #20
0
        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();
        }
Пример #21
0
        /// <summary>
        /// Creates default Configuration and Platform values based on solution configurations present in the solution
        /// </summary>
        /// <param name="msbuildProject"></param>
        /// <param name="solution"></param>
        /// <owner>LukaszG</owner>
        static private void AddConfigurationPlatformDefaults
        (
            Project msbuildProject,
            SolutionParser solution
        )
        {
            BuildPropertyGroup configurationDefaultingPropertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            configurationDefaultingPropertyGroup.Condition = " '$(Configuration)' == '' ";
            configurationDefaultingPropertyGroup.AddNewProperty("Configuration", solution.GetDefaultConfigurationName(), true /* treat as literal */);

            BuildPropertyGroup platformDefaultingPropertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            platformDefaultingPropertyGroup.Condition = " '$(Platform)' == '' ";
            platformDefaultingPropertyGroup.AddNewProperty("Platform", solution.GetDefaultPlatformName(), true /* treat as literal */);
        }
Пример #22
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);
        }
Пример #23
0
 /// <summary>
 /// Creates the default Venus configuration property based on the selected solution configuration.
 /// Unfortunately, Venus projects only expose one project configuration in the IDE (Debug) although
 /// they allow building Debug and Release from command line. This means that if we wanted to use 
 /// the project configuration from the active solution configuration for Venus projects, we'd always
 /// end up with Debug and there'd be no way to build the Release configuration. To work around this,
 /// we use a special mechanism for choosing ASP.NET project configuration: we set it to Release if
 /// we're building a Release solution configuration, and to Debug if we're building a Debug solution 
 /// configuration. The property is also settable from the command line, in which case it takes 
 /// precedence over this algorithm.
 /// </summary>
 /// <param name="msbuildProject"></param>
 /// <owner>LukaszG</owner>
 static private void AddVenusConfigurationDefaults
 (
     Project msbuildProject
 )
 {
     BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
     propertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
     propertyGroup.AddNewProperty("AspNetConfiguration", "$(Configuration)");
 }
Пример #24
0
        public override void SaveTo(Uri location)
        {
            var projectPath = location.LocalPath;
            var projectDir  = Path.GetDirectoryName(projectPath);

            var msBuildProject = new MsBuild.Project();

            msBuildProject.DefaultToolsVersion = "4.0";
            msBuildProject.DefaultTargets      = "Build";

            var propertyGroup = msBuildProject.AddNewPropertyGroup(false);

            propertyGroup.AddNewProperty("ProjectGuid", ProjectGuid.ToString("B").ToUpper());
            propertyGroup.AddNewProperty("Configuration", "Debug");
            propertyGroup.AddNewProperty("Platform", "x86");
            propertyGroup.AddNewProperty("OutputType", "Library");
            propertyGroup.AddNewProperty("RootNamespace", "VVVV.Nodes");
            propertyGroup.AddNewProperty("AssemblyName", AssemblyName);
            propertyGroup.AddNewProperty("TargetFrameworkVersion", "v4.0");
            propertyGroup.AddNewProperty("OutputPath", "bin\\Debug\\");
            propertyGroup.AddNewProperty("DebugSymbols", "True");
            propertyGroup.AddNewProperty("DebugType", "Full");
            propertyGroup.AddNewProperty("Optimize", "False");
            propertyGroup.AddNewProperty("CheckForOverflowUnderflow", "True");
            propertyGroup.AddNewProperty("DefineConstants", "DEBUG;TRACE");
            propertyGroup.AddNewProperty("AllowUnsafeBlocks", "True");

            //add loaded reference paths
            var expandedVVVV45Path = msBuildProject.GetEvaluatedProperty("ReferencePath");

            foreach (var refPath in ReferencePaths)
            {
                if (refPath != expandedVVVV45Path)
                {
                    if (Path.IsPathRooted(refPath))
                    {
                        propertyGroup.AddNewProperty("ReferencePath", PathUtils.MakeRelativePath(projectDir + @"\", refPath + @"\"));
                    }
                    else
                    {
                        propertyGroup.AddNewProperty("ReferencePath", refPath);
                    }
                }
            }

            msBuildProject.AddNewImport("$(MSBuildBinPath)\\Microsoft.CSharp.Targets", null);

            //add reference items
            foreach (var reference in References)
            {
                var item = msBuildProject.AddNewItem("Reference", reference.Name);
                if (!reference.IsGlobal && !InReferencePaths(reference.Name))
                {
                    var hintPath = reference.GetRelativePath();
                    item.SetMetadata("HintPath", hintPath);
                }
            }

            foreach (var document in Documents)
            {
                msBuildProject.AddNewItem(document.CanBeCompiled ? "Compile" : "None", document.GetRelativePath());
            }

            // Create the project directory if it doesn't exist yet.
            if (!Directory.Exists(projectDir))
            {
                Directory.CreateDirectory(projectDir);
            }

            msBuildProject.Save(projectPath);

            base.SaveTo(location);
        }
Пример #25
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)); 
                }
            }
        }
Пример #26
0
 public void RemoveImportedPropertyGroupInvalidOp()
 {
     string importedProjFilename = String.Empty;
     string mainProjFilename = String.Empty;
     try
     {
         importedProjFilename = ObjectModelHelpers.CreateTempFileOnDisk(TestData.PropertyGroup);
         mainProjFilename = ObjectModelHelpers.CreateTempFileOnDisk(TestData.Content3SimpleTargetsDefaultSpecified);
         Project mainProject = new Project(new Engine());                                         
         Project importedProject = new Project(mainProject.ParentEngine);
         mainProject.Load(mainProjFilename);
         importedProject.Load(importedProjFilename);
         BuildPropertyGroup removalGroup = importedProject.AddNewPropertyGroup(true);
         mainProject.RemoveImportedPropertyGroup(removalGroup);
     }
     finally
     {
         CompatibilityTestHelpers.RemoveFile(importedProjFilename);
         CompatibilityTestHelpers.RemoveFile(mainProjFilename);
     }
 }