예제 #1
0
        /// <summary>
        /// Verifies if the item has a trasform configured already
        /// </summary>
        /// <param name="vsProject">The current project</param>
        /// <param name="itemid">The id of the selected item inside the project</param>
        /// <returns>True if the item has a transform</returns>
        private bool IsItemTransformItem(IVsProject vsProject, uint itemid)
        {
            IVsBuildPropertyStorage buildPropertyStorage = vsProject as IVsBuildPropertyStorage;

            if (buildPropertyStorage == null)
            {
                this.LogMessageWriteLineFormat("Error obtaining IVsBuildPropertyStorage from hierarcy.");
                return(false);
            }

            string value;

            buildPropertyStorage.GetItemAttribute(itemid, IsTransformFile, out value);
            bool valueAsBool;

            if (bool.TryParse(value, out valueAsBool) && valueAsBool)
            {
                return(true);
            }

            // we need to special case web.config transform files
            string filePath;

            buildPropertyStorage.GetItemAttribute(itemid, "FullPath", out filePath);
            IEnumerable <string> configs = ProjectUtilities.GetProjectConfigurations(vsProject as IVsHierarchy);

            // If the project is a web app, check for the Web.config files added by default
            return(ProjectUtilities.IsProjectWebApp(vsProject) && PackageUtilities.IsFileTransform("web.config", Path.GetFileName(filePath), configs));
        }
예제 #2
0
        public object GetValue(string name)
        {
            var value = default(string);

            if (item != null)
            {
                Property property;
                try
                {
                    property = item.Properties.Item(name);
                }
                catch (ArgumentException)
                {
                    property = null;
                }

                if (property != null)
                {
                    return(property.Value);
                }
            }

            if (msBuild != null)
            {
                msBuild.GetItemAttribute(node.HierarchyIdentity.ItemID, name, out value);
            }

            return(value);
        }
예제 #3
0
        protected bool GetMsBuildBool(String attributeName)
        {
            String value;

            _storage.GetItemAttribute(_itemid, attributeName, out value);

            bool result = Vitevic.AssemblyEmbedder.MsBuild.Attributes.IsTrue(value);

            return(result);
        }
예제 #4
0
        private string[] LoadRunCustomToolOn()
        {
            string s;

            _storage.GetItemAttribute(_itemId, AutoRunCustomToolPackage.TargetsPropertyName, out s);
            if (s != null)
            {
                return(s.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }
            return(null);
        }
        public static string GetString(this IVsBuildPropertyStorage storage, uint itemId, string propertyName)
        {
            string runCustomToolOnBuildPropertyValue;

            if (storage.GetItemAttribute(itemId, propertyName, out runCustomToolOnBuildPropertyValue) != 0)
            {
                return(null);
            }

            return(runCustomToolOnBuildPropertyValue);
        }
예제 #6
0
        int IVsBuildPropertyStorage.GetItemAttribute(uint item, string attributeName, out string attributeValue)
        {
            attributeValue = null;
            IVsBuildPropertyStorage cfg = _innerCfg as IVsBuildPropertyStorage;

            if (cfg != null)
            {
                return(cfg.GetItemAttribute(item, attributeName, out attributeValue));
            }
            return(VSConstants.S_OK);
        }
예제 #7
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Microsoft.Build.Evaluation.Project buildProject = buildProjectInfo.GetValue(testEnv.Project, new object[0]) as Microsoft.Build.Evaluation.Project;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                MethodInfo itemMapGetter           = typeof(VisualStudio.Project.ProjectNode).GetProperty("ItemIdMap", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true);
                Microsoft.VisualStudio.Shell.EventSinkCollection itemMap = (Microsoft.VisualStudio.Shell.EventSinkCollection)itemMapGetter.Invoke(testEnv.Project, new object[0]);
                uint itemID = itemMap.Add(node);

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
예제 #8
0
        /// <summary>
        /// Creates a new transformation file and adds it to the project.
        /// </summary>
        /// <param name="hierarchy">The project hierarchy</param>
        /// <param name="selectedProjectItem">The selected item to be transformed</param>
        /// <param name="itemName">Full name of the transformation file</param>
        /// <param name="projectPath">Full path to the current project</param>
        /// <param name="addDependentUpon">Wheter to add the new file dependent upon the source file</param>
        private void AddTransformFile(
            IVsHierarchy hierarchy,
            ProjectItem selectedProjectItem,
            string itemName,
            string projectPath,
            bool addDependentUpon)
        {
            try
            {
                string transformPath  = Path.Combine(projectPath, itemName);
                string sourceFileName = selectedProjectItem.FileNames[1];

                ITransformer transformer = TransformerFactory.GetTransformer(sourceFileName, null);

                transformer.CreateTransformFile(sourceFileName, transformPath, false);

                // Add the file to the project
                // If the DependentUpon metadata is required, add it under the original file
                // If not, add it to the project
                ProjectItem addedItem = addDependentUpon ? selectedProjectItem.ProjectItems.AddFromFile(transformPath)
                                                      : selectedProjectItem.ContainingProject.ProjectItems.AddFromFile(transformPath);

                // We need to set the Build Action to None to ensure that it doesn't get published for web projects
                addedItem.Properties.Item("ItemType").Value = "None";

                IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

                if (buildPropertyStorage == null)
                {
                    this.logger.LogMessage("Error obtaining IVsBuildPropertyStorage from hierarcy.");
                }
                else if (ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(addedItem.FileNames[0], out uint addedItemId)))
                {
                    buildPropertyStorage.SetItemAttribute(addedItemId, SlowCheetahPackage.IsTransformFile, "true");

                    if (addDependentUpon)
                    {
                        // Not all projects (like CPS) set the dependent upon metadata when using the automation object
                        buildPropertyStorage.GetItemAttribute(addedItemId, SlowCheetahPackage.DependentUpon, out string dependentUponValue);
                        if (string.IsNullOrEmpty(dependentUponValue))
                        {
                            // It didm not set it
                            buildPropertyStorage.SetItemAttribute(addedItemId, SlowCheetahPackage.DependentUpon, selectedProjectItem.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.LogMessage("AddTransformFile: Exception> " + ex.Message);
            }
        }
        public static bool GetItemAttribute(this IVsBuildPropertyStorage propertyStorage, uint item, string name, bool defaultValue)
        {
            string value;
            bool   result;

            if (ErrorHandler.Succeeded(propertyStorage.GetItemAttribute(item, name, out value)) &&
                bool.TryParse(value, out result))
            {
                return(result);
            }

            return(defaultValue);
        }
예제 #10
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                Microsoft.Build.Evaluation.Project buildProject = testEnv.Project.BuildProject;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                uint itemID = node.Id;

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
예제 #11
0
        private bool IsItemTransformItem(IVsProject vsProject, uint itemid)
        {
            IVsBuildPropertyStorage buildPropertyStorage = vsProject as IVsBuildPropertyStorage;

            if (buildPropertyStorage == null)
            {
                this.LogMessageWriteLineFormat("Error obtaining IVsBuildPropertyStorage from hierarcy.");
                return(false);
            }

            bool isItemTransformFile = false;

            string value;

            buildPropertyStorage.GetItemAttribute(itemid, IsTransformFile, out value);
            if (string.Compare("true", value, true) == 0)
            {
                isItemTransformFile = true;
            }

            // we need to special case web.config transform files
            if (!isItemTransformFile)
            {
                string pattern = @"web\..+\.config";
                string filepath;
                buildPropertyStorage.GetItemAttribute(itemid, "FullPath", out filepath);
                System.IO.FileInfo fi = new System.IO.FileInfo(filepath);
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(
                    pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (regex.IsMatch(fi.Name))
                {
                    isItemTransformFile = true;
                }
            }

            return(isItemTransformFile);
        }
예제 #12
0
        private bool GetBoolValue(string propertyName)
        {
            string s;

            _storage.GetItemAttribute(_itemId, propertyName, out s);
            if (s != null)
            {
                bool bValue;
                if (bool.TryParse(s, out bValue))
                {
                    return(bValue);
                }
            }
            return(false);
        }
        public static bool?GetBoolean(this IVsBuildPropertyStorage storage, uint itemId, string propertyName)
        {
            string runCustomToolOnBuildPropertyValue;

            if (storage.GetItemAttribute(itemId, propertyName, out runCustomToolOnBuildPropertyValue) != 0)
            {
                return(null);
            }

            bool boolValue;

            if (bool.TryParse(runCustomToolOnBuildPropertyValue, out boolValue))
            {
                return(boolValue);
            }

            return(null);
        }
예제 #14
0
        protected T Get <T>(T defaultValue = default(T), Func <string, T> coercionFunc = null, [CallerMemberName] string name = null)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (!_isInitialized)
            {
                return(defaultValue);
            }

            string serializedValue;

            if (0 != _storage.GetItemAttribute(_itemId, Scope(name), out serializedValue))
            {
                return(defaultValue);
            }

            if (string.IsNullOrWhiteSpace(serializedValue))
            {
                return(defaultValue);
            }

            try
            {
                if (typeof(T).IsEnum)
                {
                    return((T)Enum.Parse(typeof(T), serializedValue));
                }
                return((T)Convert.ChangeType(serializedValue, typeof(T)));
            }
            catch
            {
                if (coercionFunc != null)
                {
                    return(coercionFunc(serializedValue));
                }

                return(defaultValue);
            }
        }
예제 #15
0
        protected T Get <T>(T defaultValue = default(T), [CallerMemberName] string name = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (!_isInitialized)
            {
                return(defaultValue);
            }

            string serializedValue;

            if (0 != _storage.GetItemAttribute(_itemId, Scope(name), out serializedValue))
            {
                return(defaultValue);
            }

            return(!String.IsNullOrWhiteSpace(serializedValue)
                       ? (T)Convert.ChangeType(serializedValue, typeof(T))
                       : defaultValue);
        }
예제 #16
0
        /// <summary>Gets name of resources class from resource logical name</summary>
        /// <param name="className">Original name of class. When this method exists this parameter is set to class name parsed from file logical name. The parameter is unchanged when logical name is not set.</param>
        private void GetClassNameFromLogicalName(ref string className)
        {
            try {
                IntPtr siteInterfacePointer;
                Guid   vsBrowseObjectGuid = typeof(IVsBrowseObject).GUID;
                GetSite(ref vsBrowseObjectGuid, out siteInterfacePointer);
                if (IntPtr.Zero != siteInterfacePointer)
                {
                    IVsHierarchy    vsHierarchy;
                    uint            pItemId;
                    IVsBrowseObject vsBrowseObject = Marshal.GetObjectForIUnknown(siteInterfacePointer) as IVsBrowseObject;

                    vsBrowseObject.GetProjectItem(out vsHierarchy, out pItemId);
                    IVsBuildPropertyStorage buildPropertyStorage = vsHierarchy as IVsBuildPropertyStorage;
                    if (buildPropertyStorage != null)
                    {
                        string LogicalName = null;
                        try {
                            buildPropertyStorage.GetItemAttribute(pItemId, "LogicalName", out LogicalName);
                        } catch { }
                        if (LogicalName != null)
                        {
                            if (LogicalName.EndsWith(".resources"))
                            {
                                LogicalName = LogicalName.Substring(0, LogicalName.Length - ".resources".Length);
                            }
                            if (LogicalName.Contains("."))
                            {
                                LogicalName = LogicalName.Substring(LogicalName.LastIndexOf('.') + 1);
                            }
                            className = LogicalName;
                        }
                    }
                }
            }catch {}
        }
예제 #17
0
        private void OnAfterAddedGrammarHelperFile(IVsProject project, string currentFile)
        {
            int found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemId;

            if (ErrorHandler.Failed(project.IsDocumentInProject(currentFile, out found, priority, out itemId)))
            {
                return;
            }

            if (found == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard)
            {
                return;
            }

            IVsHierarchy            hierarchy            = project as IVsHierarchy;
            IVsBuildPropertyStorage buildPropertyStorage = project as IVsBuildPropertyStorage;

            if (hierarchy != null && buildPropertyStorage != null)
            {
                string dependentUpon;
                if (ErrorHandler.Failed(buildPropertyStorage.GetItemAttribute(itemId, "DependentUpon", out dependentUpon)))
                {
                    string[] stripExtensions = { ".cs", ".lexer", ".parser" };
                    string   parentFileName  = Path.GetFileName(currentFile);
                    while (!string.IsNullOrWhiteSpace(parentFileName) && Array.IndexOf(stripExtensions, Path.GetExtension(parentFileName).ToLowerInvariant()) >= 0)
                    {
                        parentFileName = Path.GetFileNameWithoutExtension(parentFileName);
                    }

                    int hr = buildPropertyStorage.SetItemAttribute(itemId, "DependentUpon", parentFileName);
                }
            }
        }
        void DocumentEvents_DocumentSaved(Document doc)
        {
            var docItem = doc.ProjectItem;

            if (docItem == null)
            {
                return;
            }

            string docFullPath = (string)GetPropertyValue(docItem, "FullPath");

            var          projectName = docItem.ContainingProject.UniqueName;
            IVsSolution  solution    = (IVsSolution)GetGlobalService(typeof(SVsSolution));
            IVsHierarchy project;

            solution.GetProjectOfUniqueName(projectName, out project);

            var docErrors = _errorListProvider.Tasks.Cast <ErrorTask>().Where(t => t.Document == docFullPath).ToList();

            foreach (var errorTask in docErrors)
            {
                _errorListProvider.Tasks.Remove(errorTask);
            }

            var targets = new List <string>();

            string customTool = GetPropertyValue(docItem, "CustomTool") as string;

            if (customTool == "AutoRunCustomTool")
            {
                LogWarning(project, docFullPath, "Setting Custom Tool to 'AutoRunCustomTool' is still supported for compatibility, but is deprecated. Use the 'Run custom tool on' property instead");
                string targetName = GetPropertyValue(docItem, "CustomToolNamespace") as string;
                if (string.IsNullOrEmpty(targetName))
                {
                    LogError(project, docFullPath, "The target file is not specified. Enter its relative path in the 'Custom tool namespace' property");
                    return;
                }
                targets.Add(targetName);
            }
            else
            {
                IVsBuildPropertyStorage storage = project as IVsBuildPropertyStorage;
                if (storage == null)
                {
                    return;
                }

                uint itemId;
                if (project.ParseCanonicalName(docFullPath, out itemId) != 0)
                {
                    return;
                }

                string runCustomToolOn;
                if (storage.GetItemAttribute(itemId, TargetsPropertyName, out runCustomToolOn) != 0)
                {
                    return;
                }

                if (runCustomToolOn == null)
                {
                    return;
                }
                targets.AddRange(runCustomToolOn.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }

            foreach (var targetName in targets)
            {
                string dir = Path.GetDirectoryName(docFullPath);
                // ReSharper disable once AssignNullToNotNullAttribute
                string targetPath = Path.GetFullPath(Path.Combine(dir, targetName));
                var    targetItem = _dte.Solution.FindProjectItem(targetPath);
                if (targetItem == null)
                {
                    LogError(project, docFullPath, "Target item '{0}' was not found", targetPath);
                    continue;
                }

                string targetCustomTool = (string)GetPropertyValue(targetItem, "CustomTool");
                if (string.IsNullOrEmpty(targetCustomTool))
                {
                    LogError(project, docFullPath, "Target item '{0}' doesn't define a custom tool", targetPath);
                    continue;
                }

                var vsTargetItem = (VSProjectItem)targetItem.Object;
                LogActivity("Running custom tool on '{0}'", targetPath);
                vsTargetItem.RunCustomTool();
            }
        }
예제 #19
0
        /// <summary>Gets namespace of resource</summary>
        /// <param name="forLogicalName">Use logical name; ignored when <see cref="ResourceNamespace"/> is not null</param>
        /// <returns>Resource namespace</returns>
        protected string GetResourcesNamespace(bool forLogicalName)//forLogicalName added by Ðonny
        {
            if (this.ResourceNamespace != null)
            {
                return(ResourceNamespace);
            }
            string resourcesNamespace = null;

            try {
                IntPtr siteInterfacePointer;
                Guid   vsBrowseObjectGuid = typeof(IVsBrowseObject).GUID;
                GetSite(ref vsBrowseObjectGuid, out siteInterfacePointer);
                if (IntPtr.Zero != siteInterfacePointer)
                {
                    IVsHierarchy    vsHierarchy;
                    uint            pItemId;
                    object          propertyValue;
                    IVsBrowseObject vsBrowseObject = Marshal.GetObjectForIUnknown(siteInterfacePointer) as IVsBrowseObject;

                    vsBrowseObject.GetProjectItem(out vsHierarchy, out pItemId);
                    //Added by Ðonny:
                    //Support for <LogicalName>
                    if (forLogicalName)
                    {
                        IVsBuildPropertyStorage buildPropertyStorage = vsHierarchy as IVsBuildPropertyStorage;
                        if (buildPropertyStorage != null)
                        {
                            string LogicalName = null;
                            try {
                                buildPropertyStorage.GetItemAttribute(pItemId, "LogicalName", out LogicalName);
                            } catch { }
                            if (LogicalName != null)
                            {
                                if (LogicalName.EndsWith(".resources"))
                                {
                                    return(LogicalName.Substring(0, LogicalName.Length - ".resources".Length));
                                }
                                else
                                {
                                    return(LogicalName);
                                }
                            }
                        }
                    }

                    Marshal.Release(siteInterfacePointer);
                    if (null == vsBrowseObject)
                    {
                        return(resourcesNamespace);
                    }


                    if (null == vsHierarchy)
                    {
                        return(resourcesNamespace);
                    }

                    vsHierarchy.GetProperty(pItemId, -2049, out propertyValue);
                    string propertyText = propertyValue as string;
                    if (null == propertyText)
                    {
                        return(resourcesNamespace);
                    }

                    resourcesNamespace = propertyText;
                }
            } catch (Exception ex) {
                if (ProjectUtilities.IsCriticalException(ex))
                {
                    throw;
                }
            }

            return(resourcesNamespace);
        }
예제 #20
0
        public static XnaBuildProperties GetXnaBuildProperties(IVsHierarchy hierarchy, uint itemID)
        {
            XnaBuildProperties buildProperties = new XnaBuildProperties();

            // Get project object for specified hierarchy.
            VSProject project = GetProject(hierarchy);

            if (project == null)
            {
                throw new InvalidOperationException("Could not find content project for this item.");
            }

            // Get references from project.
            int referenceCount = project.References.Count;

            for (int i = 1; i <= referenceCount; ++i)
            {
                Reference reference = project.References.Item(i);
                buildProperties.ProjectReferences.Add(reference.Path);
            }

            IVsBuildPropertyStorage buildPropertyStorage = (IVsBuildPropertyStorage)hierarchy;

            string importer;

            buildPropertyStorage.GetItemAttribute(itemID, XnaConstants.Importer, out importer);
            if (!string.IsNullOrEmpty(importer))
            {
                buildProperties.Importer = importer;
            }

            string processor;

            buildPropertyStorage.GetItemAttribute(itemID, XnaConstants.Processor, out processor);
            if (!string.IsNullOrEmpty(processor))
            {
                buildProperties.Processor = processor;
            }

            if (buildProperties.Processor == null)
            {
                return(buildProperties);
            }

            // TODO: Look into caching ContentPipelineManager, but then we need to take care of refreshing it
            // when the content project references change.
            ContentPipelineManager contentPipelineManager = new ContentPipelineManager(project.References, XnaConstants.XnaFrameworkVersion);
            var processorParameters = contentPipelineManager.GetProcessorParameters(buildProperties.Processor);

            foreach (IParameterDescriptor processorParameter in processorParameters)
            {
                string propertyValue;
                buildPropertyStorage.GetItemAttribute(itemID, XnaConstants.ProcessorParametersPrefix + processorParameter.PropertyName, out propertyValue);
                buildProperties.ProcessorParameters.Add(XnaConstants.ProcessorParametersPrefix + processorParameter.PropertyName, propertyValue);
            }

            /*
             * // Cannot use MSBuild object model because it uses a static instance of the Engine.
             * XDocument projectDocument = XDocument.Load(project.Project.FullName);
             * string projectFolder = Path.GetDirectoryName(project.Project.FullName);
             *
             * var projectItem = projectDocument.Descendants().FirstOrDefault(n =>
             * {
             *      XAttribute attr = n.Attribute("Include");
             *      if (attr == null)
             *              return false;
             *
             *      string includeValue = attr.Value;
             *      return string.Equals(Path.Combine(projectFolder, includeValue), fileName, StringComparison.InvariantCultureIgnoreCase);
             * });
             * if (projectItem == null)
             *              throw new InvalidOperationException("Could not find item in project.");
             *
             * if (projectItem.Element(PropertyNames.Importer) != null)
             *      buildProperties.Importer = projectItem.Element(PropertyNames.Importer).Value;
             * if (projectItem.Element(PropertyNames.Processor) != null)
             *      buildProperties.Processor = projectItem.Element(PropertyNames.Processor).Value;
             *
             * foreach (XElement processorParameter in projectItem.Elements().Where(e => e.Name.LocalName.StartsWith(PropertyNames.ProcessorParametersPrefix)))
             *      buildProperties.ProcessorParameters.Add(processorParameter.Name.LocalName, processorParameter.Value);
             * */

            return(buildProperties);
        }
        /// <summary>
        /// Code from Xsd2Code.Addin::Connect
        /// </summary>
        private void openConfigurationWindow()
        {
            ProjectItem proitem          = Dte.SelectedItems.Item(1).ProjectItem;
            Project     proj             = proitem.ContainingProject;
            string      projectDirectory = Path.GetDirectoryName(proj.FullName);

            // Try to get default nameSpace
            string defaultNamespace = string.Empty;
            uint?  targetFramework  = 0;
            bool?  isSilverlightApp = false;

            try
            {
                defaultNamespace = proj.Properties.Item("DefaultNamespace").Value as string;
                targetFramework  = proj.Properties.Item("TargetFramework").Value as uint?;
                isSilverlightApp = proj.Properties.Item("SilverlightProject.IsSilverlightApplication").Value as bool?;
            }
            catch
            {
            }

            string xsdFileName = proitem.FileNames[0];

            try
            {
                proitem.Save(xsdFileName);
            }
            catch (Exception)
            {
            }

            TargetFramework framework = TargetFramework.Net20;

            if (targetFramework.HasValue)
            {
                uint target = targetFramework.Value;
                switch (target)
                {
                case 196608:
                    framework = TargetFramework.Net30;
                    break;

                case 196613:
                    framework = TargetFramework.Net35;
                    break;

                case 262144:
                    framework = TargetFramework.Net40;
                    break;
                }
            }
            if (isSilverlightApp.HasValue)
            {
                if (isSilverlightApp.Value)
                {
                    framework = TargetFramework.Silverlight;
                }
            }

            // We associate an outputfile with the selected XSD file to know were to look for the parameters
            // TODO embed all the parameters as attributes of the XSD file in the project ?
            IVsHierarchy            hierarchy = null;
            uint                    itemid;
            string                  outputFile           = null;
            IVsBuildPropertyStorage buildPropertyStorage = null;

            if (IsSingleProjectItemSelection(out hierarchy, out itemid))
            {
                buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
                if (buildPropertyStorage != null)
                {
                    buildPropertyStorage.GetItemAttribute(itemid, "Xsd2CodeOutputFile", out outputFile);
                }
            }

            var frm = new FormOption();

            frm.Init(xsdFileName, proj.CodeModel.Language, defaultNamespace, framework, Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile ?? string.Empty));

            DialogResult result = frm.ShowDialog();

            GeneratorParams generatorParams = frm.GeneratorParams.Clone();

            generatorParams.InputFilePath = xsdFileName;

            var gen = new GeneratorFacade(generatorParams);

            bool foundOutputFile = false;

            if (xsdFileName.Length > 0)
            {
                if (result == DialogResult.OK)
                {
                    // Close file if open in IDE
                    ProjectItem projElmts = null;
                    if (!String.IsNullOrEmpty(outputFile))
                    {
                        string rootedOutputFile = Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile);
                        foundOutputFile = FindInProject(proj.ProjectItems, rootedOutputFile, out projElmts);
                        if (foundOutputFile)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Close(vsSaveChanges.vsSaveChangesNo);
                        }
                    }

                    Result <List <string> > generateResult  = gen.Generate();
                    List <string>           outputFileNames = generateResult.Entity;

                    if (!generateResult.Success)
                    {
                        MessageBox.Show(generateResult.Messages.ToString(), "XSD2Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        string vsProjectOutputFilePath = outputFileNames[0];
                        // Save one of the output file path so we can read the parameters from it the next time
                        if (buildPropertyStorage != null)
                        {
                            buildPropertyStorage.SetItemAttribute(itemid, "Xsd2CodeOutputFile", GetRelativePath(vsProjectOutputFilePath, projectDirectory));
                        }

                        // try again now that the generation occured
                        string newRootedOutputFile = Path.Combine(projectDirectory, vsProjectOutputFilePath);
                        foundOutputFile = FindInProject(proj.ProjectItems, newRootedOutputFile, out projElmts);
                        if (!foundOutputFile)
                        {
                            projElmts = proj.ProjectItems.AddFromFile(newRootedOutputFile);
                        }


                        if (frm.OpenAfterGeneration && projElmts != null)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Activate();
                            window.SetFocus();

                            try
                            {
                                // this.applicationObjectField.DTE.ExecuteCommand("Edit.RemoveAndSort", "");
                                Dte.ExecuteCommand("Edit.FormatDocument", string.Empty);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            return;
        }
예제 #22
0
        public static string GetItemAttribute(this IVsBuildPropertyStorage propertyStorage, uint item, string name, string defaultValue)
        {
            string value;

            return(ErrorHandler.Succeeded(propertyStorage.GetItemAttribute(item, name, out value)) ? value : defaultValue);
        }