예제 #1
0
        public ViewModelWizard(EnvDTE.DTE dte, EnvDTE.ProjectItem viewModel, IVsPackageInstallerServices packageInstallerServices)
        {
            InitializeComponent();

            _dte = dte;
            _viewModel = viewModel;
            _packageInstallerServices = packageInstallerServices;

            var edmxs = _dte.GetSolutionEdmx(_viewModel.ContainingProject, skipWaqsAlreadyUsed: false).ToList();
            edmx.ItemsSource = edmxs;
            edmx.SelectedItem = edmxs.FirstOrDefault();

            var views = _dte.GetSolutionXaml(_viewModel.ContainingProject).ToList();
            views.Insert(0, new DTEExtensions.FilePathes { DisplayPath = "", FullPath = null });
            view.ItemsSource = views;
            view.SelectedItem = views.FirstOrDefault();
        }
예제 #2
0
        /// <summary>
        /// This handles the low-level copying of files from a project into a destination path, flattening
        /// the file structure.
        /// </summary>
        private static bool CopyProjectFiles(EnvDTE.Project proj, string destPath, string listingFile)
        {
            System.IO.StreamWriter writer = null;
            EnvDTE.ProjectItems    Items = proj.ProjectItems;
            EnvDTE.ProjectItem     Item = null;
            int    i, j, nItemCount, nFileCount;
            string strFileName = null;
            string strFilePath = null;
            bool   fSucceeded  = true;

            try
            {
                // Open for append
                writer = new System.IO.StreamWriter(listingFile, true);

                nItemCount = Items.Count;
                for (i = 1; i <= nItemCount; i++)
                {
                    Item       = Items.Item(i);
                    nFileCount = Item.FileCount;

                    for (j = 1; j <= nFileCount; j++)
                    {
                        strFilePath = Item.get_FileNames((short)j);

                        // NOTE: The item kind can be one of physical file, misc item,
                        // or solution item. However, since we're explicitly *in* the
                        // misc or solution items folders if we're here, it makes more
                        // sense just to copy any & all files that we find in the folder
                        // and are able to locate on disk.
                        // The only exception is HTTP-based URLs, which we explicitly
                        // pick out and add to the listing file, which is deployed
                        // with all submitted assignments.
                        if ((new System.IO.FileInfo(strFilePath)).Exists)
                        {
                            strFileName = strFilePath.Substring(System.Math.Max(strFilePath.LastIndexOf('/'), strFilePath.LastIndexOf('\\')));
                            System.IO.File.Copy(strFilePath, destPath + strFileName);
                            writer.WriteLine(strFileName);
                        }
                        else
                        {
                            if (strFilePath.ToUpper().StartsWith("HTTP://"))
                            {
                                writer.WriteLine(strFilePath);
                            }
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                fSucceeded = false;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            return(fSucceeded);
        }
        protected override void OnClosed(EventArgs e)
        {
            if (_savedChanges)
            {
                // Make sure the current document has the necessary
                // extensions loaded.
                // UNDONE: We should be able to do this with the document
                // closed or open as text as well via a registered service
                // on the ORMDesignerPackage, but this is sufficient for now.
                Dictionary <string, string> requiredExtensions = null;
                string[] loadedExtensions = null;
                foreach (IORMGenerator selectedGenerator in _mainBranch.SelectedGenerators)
                {
                    foreach (string requiredExtension in selectedGenerator.GetRequiredExtensionsForInputFormat("ORM"))
                    {
                        if (loadedExtensions == null)
                        {
                            loadedExtensions = (new ORMExtensionManager(_projectItem)).GetLoadedExtensions(_serviceProvider);
                        }
                        if (Array.BinarySearch <string>(loadedExtensions, requiredExtension) < 0)
                        {
                            if (requiredExtensions == null)
                            {
                                requiredExtensions = new Dictionary <string, string>();
                            }
                            else if (requiredExtensions.ContainsKey(requiredExtension))
                            {
                                continue;
                            }
                            requiredExtensions.Add(requiredExtension, requiredExtension);
                        }
                    }
                }
                if (requiredExtensions != null)
                {
                    _savedChanges = ORMExtensionManager.EnsureExtensions(_projectItem, _serviceProvider, requiredExtensions.Values);
                }
            }
            if (_savedChanges)
            {
                // Delete the removed items from the project
                if (_removedItems != null)
                {
                    EnvDTE.ProjectItems subItems = _projectItem.ProjectItems;
                    foreach (string itemName in _removedItems.Keys)
                    {
                        try
                        {
                            EnvDTE.ProjectItem subItem = subItems.Item(itemName);
                            if (subItem != null)
                            {
                                subItem.Delete();
                            }
                        }
                        catch (ArgumentException)
                        {
                            // Swallow
                        }
                    }
                }
                // throw away the original build item group
                if (_originalItemGroup != null)
                {
                    try
                    {
#if VISUALSTUDIO_10_0
                        _project.RemoveChild(_originalItemGroup);
#else
                        _project.RemoveItemGroup(_originalItemGroup);
#endif
                    }
                    catch (InvalidOperationException)
                    {
                        // Swallow
                    }
                }

#if VISUALSTUDIO_10_0
                Dictionary <string, ProjectItemElement> removeItems = new Dictionary <string, ProjectItemElement>();
#else
                Dictionary <string, BuildItem> removeItems = new Dictionary <string, BuildItem>();
#endif
                string tmpFile = null;
                try
                {
                    EnvDTE.ProjectItems projectItems = _projectItem.ProjectItems;
#if VISUALSTUDIO_10_0
                    string itemDirectory = (new FileInfo((string)_project.FullPath)).DirectoryName;
                    foreach (ProjectItemElement item in _itemGroup.Items)
#else
                    string itemDirectory = (new FileInfo((string)_project.FullFileName)).DirectoryName;
                    foreach (BuildItem item in this._itemGroup)
#endif
                    {
                        string filePath = string.Concat(itemDirectory, Path.DirectorySeparatorChar, item.Include);
                        string fileName = (new FileInfo(item.Include)).Name;
                        if (File.Exists(filePath))
                        {
                            try
                            {
                                projectItems.AddFromFile(filePath);
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                        else
                        {
                            if (tmpFile == null)
                            {
                                tmpFile = Path.GetTempFileName();
                            }
                            EnvDTE.ProjectItem projectItem = projectItems.AddFromTemplate(tmpFile, fileName);
                            string             customTool  = item.GetMetadata(ITEMMETADATA_GENERATOR);
                            if (!string.IsNullOrEmpty(customTool))
                            {
                                projectItem.Properties.Item("CustomTool").Value = customTool;
                            }
                        }
                        removeItems[item.Include] = null;
                    }
                }
                finally
                {
                    if (tmpFile != null)
                    {
                        File.Delete(tmpFile);
                    }
                }

#if VISUALSTUDIO_10_0
                foreach (ProjectItemGroupElement group in this._project.ItemGroups)
#else
                foreach (BuildItemGroup group in this._project.ItemGroups)
#endif
                {
                    if (group.Condition.Trim() == this._itemGroup.Condition.Trim())
                    {
                        continue;
                    }
#if VISUALSTUDIO_10_0
                    foreach (ProjectItemElement item in group.Items)
#else
                    foreach (BuildItem item in group)
#endif
                    {
                        if (removeItems.ContainsKey(item.Include))
                        {
                            removeItems[item.Include] = item;
                        }
                    }
                }
                foreach (string key in removeItems.Keys)
                {
#if VISUALSTUDIO_10_0
                    ProjectItemElement      removeItem;
                    ProjectElementContainer removeFrom;
                    if (null != (removeItem = removeItems[key]) &&
                        null != (removeFrom = removeItem.Parent))
                    {
                        removeFrom.RemoveChild(removeItem);
                    }
#else
                    BuildItem removeItem = removeItems[key];
                    if (removeItem != null)
                    {
                        _project.RemoveItem(removeItem);
                    }
#endif
                }

                VSLangProj.VSProjectItem vsProjectItem = _projectItem.Object as VSLangProj.VSProjectItem;
                if (vsProjectItem != null)
                {
                    vsProjectItem.RunCustomTool();
                }
            }
            else
            {
#if VISUALSTUDIO_10_0
                _project.RemoveChild(_itemGroup);
#else
                _project.RemoveItemGroup(_itemGroup);
#endif
            }
            base.OnClosed(e);
        }
예제 #4
0
        /// <summary>
        /// If we didn't find the project item at the top level, then we look one more level down.
        /// In VS files can have other nested files like foo.aspx and foo.aspx.cs or web.config and web.debug.config.
        /// These are actually top level files in the file system but are represented as nested project items in VS.
        /// </summary>
        private static bool TryGetNestedFile(EnvDTE.ProjectItems envDTEProjectItems, string name, out EnvDTE.ProjectItem envDTEProjectItem)
        {
            string parentFileName;

            if (!KnownNestedFiles.TryGetValue(name, out parentFileName))
            {
                parentFileName = Path.GetFileNameWithoutExtension(name);
            }

            // If it's not one of the known nested files then we're going to look up prefixes backwards
            // i.e. if we're looking for foo.aspx.cs then we look for foo.aspx then foo.aspx.cs as a nested file
            var parentEnvDTEProjectItem = GetProjectItem(envDTEProjectItems, parentFileName, FileKinds);

            if (parentEnvDTEProjectItem != null)
            {
                // Now try to find the nested file
                envDTEProjectItem = GetProjectItem(parentEnvDTEProjectItem.ProjectItems, name, FileKinds);
            }
            else
            {
                envDTEProjectItem = null;
            }

            return(envDTEProjectItem != null);
        }
예제 #5
0
        private static bool TryGetFolder(EnvDTE.ProjectItems envDTEProjectItems, string name, out EnvDTE.ProjectItem envDTEProjectItem)
        {
            envDTEProjectItem = GetProjectItem(envDTEProjectItems, name, FolderKinds);

            return(envDTEProjectItem != null);
        }
예제 #6
0
 public ORMExtensionManager(EnvDTE.ProjectItem projectItem, EnvDTE.Document document, Stream stream)
 {
     myProjectItem = projectItem;
     myDocument    = document;
     myStream      = stream;
 }
예제 #7
0
 public void ProjectItemFinishedGenerating(ProjectItem projectItem) { }
예제 #8
0
 public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #9
0
        private void GenerateClick(object sender, RoutedEventArgs e)
        {
            var originalCursor = Cursor;

            try
            {
                Cursor = Cursors.Wait;
                _packageInstaller.InstallPackage(_project, "WAQS.Server.Mock", _packageInstallerServices);

                var edmxPath   = edmx.SelectedValue as string;
                var appKind    = _project.Properties.Cast <EnvDTE.Property>().Any(p => p.Name.StartsWith("WebApplication")) ? "Web" : "App";
                var netVersion = _project.GetNetVersion();
                var kind       = (GenerationOptions.KindViewModel)generationOptions.SelectedItem;

                var                projectDirectoryPath = Path.GetDirectoryName(_project.FullName);
                string             waqsDirectory;
                string             waqsGeneralDirectory = null;
                string             edmxName             = null;
                EnvDTE.ProjectItem edmxProjectItem      = null;
                string             edmxProjectPath      = null;
                if (kind.Kind == GenerationOptions.Kind.FrameworkOnly)
                {
                    waqsDirectory = Path.Combine(projectDirectoryPath, "WAQS.Framework");
                }
                else
                {
                    if (!(edmxPath.EndsWith(".edmx") && File.Exists(edmxPath)))
                    {
                        ShowError("Edmx path is not correct");
                        return;
                    }
                    edmxName        = Path.GetFileNameWithoutExtension(edmxPath);
                    waqsDirectory   = Path.Combine(projectDirectoryPath, "WAQS." + edmxName);
                    edmxProjectItem = _dte.Solution.FindProjectItem(edmxPath);
                    edmxProjectPath = edmxProjectItem.ContainingProject.FullName;
                }
                if (Directory.Exists(waqsDirectory))
                {
                    ShowError(waqsDirectory + "already exists");
                    return;
                }

                var projectUIHierarchyItems    = _dte.GetProjectsUIHierarchyItems().First(uihi => ((EnvDTE.Project)uihi.Object).FullName == _project.FullName).UIHierarchyItems;
                var referencesUIHierarchyItems = projectUIHierarchyItems.Cast <EnvDTE.UIHierarchyItem>().First(uihi => uihi.Name == "References").UIHierarchyItems;
                var referencesExpanded         = referencesUIHierarchyItems.Expanded;

                var toolsPath           = Path.Combine(_packageInstallerServices.GetPackageLocation("WAQS.Server.Mock"), "tools");
                var toolsPathServerMock = Path.Combine(toolsPath, "Server.Mock");
                var defaultNamespace    = _project.GetDefaultNamespace();
                var references          = ((VSProject)_project.Object).References;
                references.Add("System");
                references.Add("System.Core");
                references.Add("System.Data");
                references.Add("Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll");
                var dalInterfacesProjectItem = _dte.Solution.FindProjectItem(edmxName + ".Server.DAL.Interfaces.tt");
                var dalInterfacesProject     = dalInterfacesProjectItem?.ContainingProject;
                if (dalInterfacesProject != null)
                {
                    references.AddProject(dalInterfacesProject);
                }
                var dalProjectItem = _dte.Solution.FindProjectItem(edmxName + ".Server.DAL.tt");
                var dalProject     = dalProjectItem?.ContainingProject;
                if (dalProject != null)
                {
                    references.AddProject(dalProject);
                }
                var dtoProject = _dte.Solution.FindProjectItem(edmxName + ".Server.DTO.tt")?.ContainingProject;
                if (dtoProject != null)
                {
                    references.AddProject(dtoProject);
                }
                var entitiesProjectItem = _dte.Solution.FindProjectItem(edmxName + ".Server.Entities.tt");
                var entitiesProject     = entitiesProjectItem?.ContainingProject;
                if (entitiesProject != null)
                {
                    references.AddProject(entitiesProject);
                }
                var serviceProject = _dte.Solution.FindProjectItem(edmxName + ".Server.Service.tt")?.ContainingProject;
                if (serviceProject != null)
                {
                    references.AddProject(serviceProject);
                }
                EnvDTE.Project fxProject = null;
                if (kind.Kind == GenerationOptions.Kind.WithoutGlobalWithoutFramework)
                {
                    fxProject = _dte.Solution.FindProjectItem("WAQS.Server.Fx.DAL.Mock.tt")?.ContainingProject;
                    if (fxProject != null)
                    {
                        references.AddProject(fxProject);
                    }
                }
                _packageInstaller.InstallPackage("http://packages.nuget.org", _project, "EntityFramework", "6.1.2", false);
                try
                {
                    referencesUIHierarchyItems.Expanded = referencesExpanded;
                }
                catch
                {
                }
                string vsVersion;
                switch (_dte.Version)
                {
                case "12.0":
                    vsVersion = "VS12";
                    break;

                case "14.0":
                default:
                    vsVersion = "VS14";
                    break;
                }

                var entitiesProjectPath  = entitiesProject.FullName;
                var entitiesSolutionPath = entitiesProject == null ? null : _dte.Solution.FileName;

                var exePath = Path.Combine(toolsPathServerMock, "InitWAQSServerMock.exe");
                var exeArgs = new StringBuilder("\"" + edmxPath + "\" \"" + projectDirectoryPath + "\" \"" + toolsPathServerMock + "\" \"" + defaultNamespace + "\" \"" + waqsDirectory + "\" \"" + waqsGeneralDirectory + "\" \"" + entitiesSolutionPath + "\" \"" + entitiesProjectPath + "\" \"" + netVersion + "\" \"" + vsVersion + "\" \"" + kind.Key + "\" \"" + (copyTemplates.IsChecked == true ? "WithSourceControl" : "WithoutSourceControl") + "\" \"" + _dte.Solution.FullName + "\"");
                if ((kind.Kind & GenerationOptions.Kind.WithoutGlobalWithoutFramework) != 0)
                {
                    var specificationsProjectItem = entitiesProject?.GetAllProjectItems().FirstOrDefault(pi => ((string)pi.Properties.Cast <EnvDTE.Property>().First(p => p.Name == "FullPath").Value).EndsWith("\\Specifications\\"));
                    exeArgs.Append(" \"" + specificationsProjectItem?.ContainingProject.FullName + "\"");
                    exeArgs.Append(" \"" + specificationsProjectItem?.GetFilePath() + "\"");
                    var dtoProjectItem = (dtoProject ?? entitiesProject).GetAllProjectItems().FirstOrDefault(pi => ((string)pi.Properties.Cast <EnvDTE.Property>().First(p => p.Name == "FullPath").Value).EndsWith("\\DTO\\"));
                    exeArgs.Append(" \"" + dtoProjectItem?.ContainingProject.FullName + "\"");
                    exeArgs.Append(" \"" + dtoProjectItem?.GetFilePath() + "\"");
                    var entityCsProjectItem = entitiesProjectItem?.ProjectItems.Cast <EnvDTE.ProjectItem>().FirstOrDefault(pi => pi.Name.EndsWith(".cs"));
                    exeArgs.Append(" \"" + entityCsProjectItem?.GetFilePath() + "\"");
                    var dalInterfaceCsProjectItem = dalInterfacesProjectItem?.ProjectItems.Cast <EnvDTE.ProjectItem>().FirstOrDefault(pi => pi.Name.EndsWith(".cs"));
                    exeArgs.Append(" \"" + dalInterfaceCsProjectItem?.GetFilePath() + "\"");
                    var dalCsProjectItem = dalProjectItem?.ProjectItems.Cast <EnvDTE.ProjectItem>().FirstOrDefault(pi => pi.Name.EndsWith(".cs"));
                    exeArgs.Append(" \"" + dalCsProjectItem?.GetFilePath() + "\"");
                    exeArgs.Append(" \"" + edmxProjectPath + "\"");
                    var configProjectItem = edmxProjectItem.ContainingProject.ProjectItems.Cast <EnvDTE.ProjectItem>().FirstOrDefault(pi => string.Equals(pi.Name, "App.config", StringComparison.CurrentCultureIgnoreCase) || string.Equals(pi.Name, "Web.config", StringComparison.CurrentCultureIgnoreCase));
                    exeArgs.Append(" \"" + configProjectItem?.GetFilePath() + "\"");
                }
                var process = new Process();
                process.StartInfo.FileName    = exePath;
                process.StartInfo.Arguments   = exeArgs.ToString();
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.Start();
                process.WaitForExit();

                if (copyTemplates.IsChecked == true)
                {
                    string              templatesFolder;
                    HashSet <string>    existingTTIncludes;
                    EnvDTE.ProjectItems templatesProjectItems;
                    TemplatesCopying.CopyTemplates(_dte, "ServerMockTemplates", netVersion, toolsPath, vsVersion, out templatesFolder, out existingTTIncludes, out templatesProjectItems);
                    var ttInclude     = @"%AppData%\WAQS\Templates\Includes\WAQS.Roslyn.Assemblies.ttinclude";
                    var ttIncludeName = Path.GetFileName(ttInclude);
                    TemplatesCopying.AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
                }

                if (kind.Kind == GenerationOptions.Kind.FrameworkOnly)
                {
                    edmxName = "Framework";
                }
                _project.ProjectItems.AddFromFile(Path.Combine(waqsDirectory, edmxName + ".Server.Mock.waqs"));
                _project.ProjectItems.AddFromFile(Path.Combine(waqsDirectory, edmxName + ".Server.Mock.tt"));
                try
                {
                    projectUIHierarchyItems.Cast <EnvDTE.UIHierarchyItem>().First(uihi => uihi.Name == "WAQS." + edmxName).UIHierarchyItems.Expanded = false;
                }
                catch
                {
                }
                try
                {
                    _dte.ExecuteCommand("File.TfsRefreshStatus");
                }
                catch
                {
                }
                _dte.ItemOperations.Navigate("https://github.com/MatthieuMEZIL/waqs/blob/master/README.md");
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().ToString() + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                Cursor = originalCursor;
            }
        }
예제 #10
0
        /// <summary>
        /// Generate a code file for the current xml file contents. Loads
        /// settings for the file off the Plix.xml settings file in the project to
        /// get the generation transform and other settings to apply to the specific file.
        /// </summary>
        /// <param name="fileContents">Contents of an xml file to transform</param>
        /// <param name="defaultNamespace">The namespace provided in the property grid</param>
        /// <returns>Contents of the corresponding code file</returns>
        private string GenerateCode(string fileContents, string defaultNamespace)
        {
                        #if VerifyUIThread
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        #endif

            // Make sure we have a CodeDomProvider
            CodeDomProvider provider = CodeDomProvider;
            if (provider == null)
            {
                return(string.Empty);
            }

            // Get the current project item and project information
            EnvDTE.ProjectItem projectItem     = CurrentProjectItem;
            string             sourceFile      = (string)projectItem.Properties.Item("LocalPath").Value;
            EnvDTE.Project     project         = projectItem.ContainingProject;
            string             projectFile     = (string)project.Properties.Item("LocalPath").Value;
            string             projectLocation = projectFile.Substring(0, projectFile.LastIndexOf('\\') + 1);

            // If this is the Plix.xml settings file, then regenerate all other mentioned NUPlixLoader files
            if (0 == string.Compare(projectItem.Name, PlixProjectSettingsFile, true, CultureInfo.InvariantCulture))
            {
                RunCustomTool(
                    project.ProjectItems,
                    projectItem,
                    delegate(EnvDTE.ProjectItem matchItem)
                {
                                                #if VerifyUIThread
                    Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                #endif

                    VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                    if (vsProjItem != null)
                    {
                        vsProjItem.RunCustomTool();
                    }
                });
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(
                                                       @"Empty file generated by NUPlixLoader for Plix.xml.

Setting NUPlixLoader as the custom tool on the Plix.xml settings file enables automatic
regeneration of other NUPlixLoader files in the project when the settings file is changed.

There is no way to both successfully trigger regeneration and avoid writing this file."), writer, null);
                return(writer.ToString());
            }

            // Load a language formatter for this file extension
            string fileExtension = CodeDomProvider.FileExtension;
            if (fileExtension.StartsWith("."))
            {
                fileExtension = fileExtension.Substring(1);
            }
            XslCompiledTransform formatter = FormatterManager.GetFormatterTransform(fileExtension);
            if (formatter == null)
            {
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "A PLiX formatter transform for the '{0}' language was not found.", fileExtension)), writer, null);
                return(writer.ToString());
            }

            // Get options for this xml file
            XsltArgumentList arguments = new XsltArgumentList();
            string           automationObjectName;
            string           transformFile = LoadProjectSettings(sourceFile, projectLocation, arguments, project, out automationObjectName);

            // MSBUG: Beta2 There's a nasty bug with single-file generators right now where
            // the text for an open file that is not in a text document is
            // passed through as encoded bytes in the string.
            EnvDTE.Document itemDocument = projectItem.Document;
            if (itemDocument != null && "XML" != itemDocument.Language)
            {
                if (fileContents.Length > 1)
                {
                    char[]   leadChars = fileContents.ToCharArray(0, 2);
                    byte[]   leadBytes = new byte[2 * sizeof(char)];
                    GCHandle handle    = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                    Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), 2);
                    handle.Free();
                    EncodingInfo[] encodingInfos  = Encoding.GetEncodings();
                    int            encodingsCount = encodingInfos.Length;
                    for (int i = 0; i < encodingsCount; ++i)
                    {
                        EncodingInfo encodingInfo      = encodingInfos[i];
                        Encoding     encoding          = encodingInfo.GetEncoding();
                        byte[]       preamble          = encoding.GetPreamble();
                        int          preambleByteCount = preamble.Length;
                        if (preambleByteCount != 0)
                        {
                            Debug.Assert(preambleByteCount <= 4);
                            int j;
                            for (j = 0; j < preambleByteCount; ++j)
                            {
                                if (preamble[j] != leadBytes[j])
                                {
                                    break;
                                }
                            }
                            if (j == preambleByteCount)
                            {
                                Decoder decoder = encoding.GetDecoder();
                                leadChars = fileContents.ToCharArray();
                                int startCharCount = leadChars.Length;
                                leadBytes = new byte[startCharCount * sizeof(char)];
                                int      byteCount = leadBytes.Length - preambleByteCount;
                                GCHandle handle2   = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                                Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), startCharCount);
                                handle2.Free();
                                int    finalCharCount = decoder.GetCharCount(leadBytes, preambleByteCount, byteCount, true);
                                char[] finalChars     = new char[finalCharCount + 1];
                                decoder.GetChars(leadBytes, preambleByteCount, byteCount, finalChars, 0, true);

                                // Hack within a hack to make sure that the Xml element has a trailing >,
                                // byte data in a string has a tendency to lose the last byte
                                char testChar = finalChars[finalCharCount - 1];;
                                if (testChar != '>' && !char.IsWhiteSpace(testChar))
                                {
                                    finalChars[finalCharCount] = '>';
                                    ++finalCharCount;
                                }
                                fileContents = new string(finalChars, 0, finalCharCount);
                            }
                        }
                    }
                }
            }

            // Resolve any file redirections here. File redirection allows the same source file
            // to generate multiple outputs via multiple transforms.
            string alternateSourceFile = null;
            using (StringReader stringReader = new StringReader(fileContents))
            {
                try
                {
                    using (XmlTextReader reader = new XmlTextReader(stringReader))
                    {
                        if (XmlNodeType.Element == reader.MoveToContent())
                        {
                            if (reader.NamespaceURI == RedirectNamespace &&
                                reader.LocalName == RedirectElementName)
                            {
                                string   relativeTargetSourceFile = reader.GetAttribute(RedirectTargetAttribute);
                                FileInfo targetSourceFileInfo     = new FileInfo(sourceFile.Substring(0, sourceFile.LastIndexOf('\\') + 1) + relativeTargetSourceFile);
                                if (targetSourceFileInfo.Exists)
                                {
                                    alternateSourceFile = targetSourceFileInfo.FullName;
                                    sourceFile          = alternateSourceFile;
                                    try
                                    {
                                        itemDocument = null;
                                        itemDocument = project.DTE.Documents.Item(alternateSourceFile);
                                    }
                                    catch (ArgumentException)
                                    {
                                        // Swallow if the document is not open
                                    }
                                }
                                else
                                {
                                    StringWriter writer = new StringWriter();
                                    provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "Redirection target file '{0}' not found", relativeTargetSourceFile)), writer, null);
                                    return(writer.ToString());
                                }
                            }
                        }
                    }
                }
                catch (XmlException ex)
                {
                    return(GenerateExceptionInformation(ex, provider));
                }
            }

            // Add standard defined attributes to the argument list
            string projectNamespace = (string)project.Properties.Item("DefaultNamespace").Value;
            if (null == arguments.GetParam("ProjectPath", ""))
            {
                arguments.AddParam("ProjectPath", "", projectLocation);
            }
            if (null == arguments.GetParam("SourceFile", ""))
            {
                arguments.AddParam("SourceFile", "", sourceFile.Substring(projectLocation.Length));
            }
            if (null == arguments.GetParam("CustomToolNamespace", ""))
            {
                if (defaultNamespace == null || defaultNamespace.Length == 0)
                {
                    defaultNamespace = projectNamespace;
                }
                arguments.AddParam("CustomToolNamespace", "", defaultNamespace);
            }
            if (null == arguments.GetParam("ProjectNamespace", ""))
            {
                arguments.AddParam("ProjectNamespace", "", projectNamespace);
            }

            try
            {
                XslCompiledTransform transform = null;
                if (transformFile != null)
                {
                    transform = new XslCompiledTransform();
                    using (FileStream transformStream = new FileStream(transformFile, FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader reader = new StreamReader(transformStream))
                        {
                            transform.Load(new XmlTextReader(reader), XsltSettings.TrustedXslt, XmlUtility.CreateFileResolver(transformFile));
                        }
                    }
                }
                MemoryStream plixStream = (transform != null) ? new MemoryStream() : null;
                using (XmlWriter xmlTextWriter = (transform != null) ? XmlWriter.Create(plixStream, transform.OutputSettings) : null)
                {
                    // Variables that need to be disposed
                    TextReader reader    = null;
                    Stream     docStream = null;

                    try
                    {
                        // First try to get data from the live object
                        string docText = null;
                        if (itemDocument != null)
                        {
                            if (automationObjectName != null)
                            {
                                docStream = itemDocument.Object(automationObjectName) as Stream;
                                if (docStream != null)
                                {
                                    reader = new StreamReader(docStream);
                                }
                            }

                            // Fall back on getting the contents of the text buffer from the live document
                            if (reader == null)
                            {
                                EnvDTE.TextDocument textDoc = itemDocument.Object("TextDocument") as EnvDTE.TextDocument;
                                if (textDoc != null)
                                {
                                    docText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                                    reader  = new StringReader(docText);
                                }
                            }
                        }

                        // If this is a redirection, then pull direction from the file
                        if (reader == null && alternateSourceFile != null)
                        {
                            reader = new StreamReader(alternateSourceFile);
                        }

                        // Fallback on the default reading mechanism
                        if (reader == null)
                        {
                            docText = fileContents;
                            reader  = new StringReader(fileContents);
                        }

                        if (transform == null)
                        {
                            XmlReaderSettings testPlixDocumentReaderSettings = new XmlReaderSettings();
                            testPlixDocumentReaderSettings.CloseInput = false;
                            bool plixDocument = false;
                            try
                            {
                                using (XmlReader testPlixDocumentReader = XmlReader.Create(reader, testPlixDocumentReaderSettings))
                                {
                                    testPlixDocumentReader.MoveToContent();
                                    if (testPlixDocumentReader.NodeType == XmlNodeType.Element && testPlixDocumentReader.NamespaceURI == PlixSchemaNamespace)
                                    {
                                        plixDocument = true;
                                    }
                                }
                            }
                            catch (XmlException ex)
                            {
                                return(GenerateExceptionInformation(ex, provider));
                            }
                            if (!plixDocument)
                            {
                                StringWriter writer = new StringWriter();
                                provider.GenerateCodeFromStatement(new CodeCommentStatement("Transform file not found"), writer, null);
                                GenerateNUPlixLoaderExceptionLine(writer, provider);
                                return(writer.ToString());
                            }
                            if (docText != null)
                            {
                                reader.Dispose();
                                reader = new StringReader(docText);
                            }
                            else
                            {
                                StreamReader streamReader = (StreamReader)reader;
                                streamReader.BaseStream.Position = 0;
                            }
                        }
                        else
                        {
                            // Use an XmlTextReader here instead of an XPathDocument
                            // so that our transforms support the xsl:preserve-space element
                            transform.Transform(new XmlTextReader(reader), arguments, xmlTextWriter, XmlUtility.CreateFileResolver(sourceFile));
                            plixStream.Position = 0;
                        }
                        // From the plix stream, generate the code
                        using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            using (XmlReader plixReader = (plixStream != null) ? XmlReader.Create(plixStream, PlixReaderSettings) : XmlReader.Create(reader, PlixReaderSettings))
                            {
                                formatter.Transform(plixReader, new XsltArgumentList(), writer);
                            }
                            return(writer.ToString());
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            (reader as IDisposable).Dispose();
                        }
                        if (docStream != null)
                        {
                            (docStream as IDisposable).Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(GenerateExceptionInformation(ex, provider));
            }
            finally
            {
                // Regardless of how we finish process this file, we need to find files redirected to this
                // one and regenerate them.
                if (alternateSourceFile == null)                 // We only redirect one level
                {
                    FileInfo sourceFileInfo = new FileInfo(sourceFile);
                    RunCustomTool(
                        project.ProjectItems,
                        projectItem,
                        delegate(EnvDTE.ProjectItem matchItem)
                    {
                                                        #if VerifyUIThread
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                        #endif

                        VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                        if (vsProjItem != null)
                        {
                            string itemFile = (string)matchItem.Properties.Item("LocalPath").Value;
                            EnvDTE.Document liveDoc;
                            EnvDTE.TextDocument textDoc;
                            string liveText = null;
                            if (null != (liveDoc = matchItem.Document) &&
                                null != (textDoc = liveDoc.Object("TextDocument") as EnvDTE.TextDocument))
                            {
                                liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                            }
                            try
                            {
                                using (FileStream fileStream = (liveText == null) ? new FileStream(itemFile, FileMode.Open, FileAccess.Read) : null)
                                {
                                    using (XmlTextReader reader = new XmlTextReader((liveText == null) ? new StreamReader(fileStream) as TextReader : new StringReader(liveText)))
                                    {
                                        if (XmlNodeType.Element == reader.MoveToContent())
                                        {
                                            if (reader.NamespaceURI == RedirectNamespace &&
                                                reader.LocalName == RedirectElementName)
                                            {
                                                FileInfo targetSourceFileInfo = new FileInfo(itemFile.Substring(0, itemFile.LastIndexOf('\\') + 1) + reader.GetAttribute(RedirectTargetAttribute));
                                                if (0 == string.Compare(sourceFileInfo.FullName, targetSourceFileInfo.FullName, true, CultureInfo.CurrentCulture))
                                                {
                                                    vsProjItem.RunCustomTool();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (XmlException)
                            {
                                // Swallow anything that Xml gripes about
                            }
                        }
                    });
                }
            }
        }
예제 #11
0
 public void AddProject([NotNull] string projectName, [NotNull] EnvDTE.ProjectItem projectItem)
 {
     _projectItems.Add(projectItem);
     ProjectName += @", " + projectName;
 }
예제 #12
0
        public void Init(
           EnvDTE.ProjectItem projItem,
           Database cloneDB,
           Cube cloneCube)
        {
            this.projItem = projItem;
            Cube selectedCube = projItem.Object as Cube;
            if ((selectedCube != null) && (selectedCube.ParentServer != null))
            {
                // if we are in Online mode there will be a parent server
                liveServer = selectedCube.ParentServer;
                liveDB = selectedCube.Parent;
                liveCube = selectedCube;

                try
                {
                    adomdConnection = new AdomdConnection(liveServer.ConnectionString + ";Initial Catalog=" + liveDB.Name);
                    adomdConnection.Open();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error connecting ADOMD.NET to server with connection string: " + liveServer.ConnectionString, ex);
                }
            }
            else
            {
                // if we are in Project mode we will use the server name from 
                // the deployment settings
                DeploymentSettings deploySet = new DeploymentSettings(projItem);
                liveServer = new Server();

                try
                {
                    liveServer.Connect(deploySet.TargetServer);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error connecting AMO to server from deployment properties: " + deploySet.TargetServer, ex);
                }
                
                liveDB = liveServer.Databases.GetByName(deploySet.TargetDatabase);
                liveCube = liveDB.Cubes.GetByName(selectedCube.Name);

                try
                {
                    adomdConnection = new AdomdConnection("Data Source=" + deploySet.TargetServer + ";Initial Catalog=" + deploySet.TargetDatabase);
                    adomdConnection.Open();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error connecting ADOMD.NET to server from deployment properties: " + deploySet.TargetServer, ex);
                }
            }
            sCubePath = liveServer.ID + "." + liveDB.ID + "." + liveCube.ID + ".";

            this.cloneDB = cloneDB;
            this.cloneCube = cloneDB.Cubes[liveCube.ID];

            this.lblServer.Text = liveServer.Name;
            this.lblDatabaseName.Text = this.liveDB.Name;
            this.iWindowFullHeight = this.Height;
            this.iWindowShortHeight = this.btnExecute.Bottom + 40;
            this.Height = iWindowShortHeight;
            this.iWindowFullWidth = this.Width;
            this.iWindowNarrowWidth = this.grpProgress.Left - 30;
            this.Width = iWindowNarrowWidth;
            this.buttonCancel.Visible = false;
            this.buttonOK.Visible = false;
            this.treeViewAggregation.Visible = false;
            this.lblUnusedAggregationsToDelete.Visible = false;
        }
            /// <summary>
            /// Creates an instance of the VsEntityFrameworkTemplateFileManager class with the IDynamicHost instance
            /// </summary>
            public VsEntityFrameworkTemplateFileManager(object textTemplating)
                : base(textTemplating)
            {
                var hostServiceProvider = _textTransformation.Host.AsIServiceProvider();
                if (hostServiceProvider == null)
                {
                    throw new ArgumentNullException("Could not obtain hostServiceProvider");
                }

                dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
                if (dte == null)
                {
                    throw new ArgumentNullException("Could not obtain DTE from host");
                }

                templateProjectItem = dte.Solution.FindProjectItem(_textTransformation.Host.TemplateFile);

                checkOutAction = fileName => dte.SourceControl.CheckOutItem(fileName);
                projectSyncAction = keepFileNames => ProjectSync(templateProjectItem, keepFileNames);
            }
예제 #14
0
		public ORMExtensionManager(EnvDTE.ProjectItem projectItem)
		{
			myProjectItem = projectItem;
		}
예제 #15
0
		public ORMExtensionManager(EnvDTE.ProjectItem projectItem, EnvDTE.Document document, Stream stream)
		{
			myProjectItem = projectItem;
			myDocument = document;
			myStream = stream;
		}
예제 #16
0
        public static string GetCustomTool(this EnvDTE.ProjectItem projectItem)
        {
            Contract.Requires(projectItem != null);

            return(GetProperty(projectItem, @"CustomTool") as string);
        }
예제 #17
0
 public void ProjectItemFinishedGenerating(ProjectItem projectItem)
 {
     AssertWizard();
     _wizard?.ProjectItemFinishedGenerating(projectItem);
 }
예제 #18
0
 // Allow post-creation adjustment of the generated project sub-items...
 protected virtual void AdjustChildItem(TIter tIter, EnvDTE.ProjectItem childItem)
 {
     // nothing by default...
 }
예제 #19
0
 public void ProjectItemFinishedGenerating(ProjectItem projectItem) {
     if (_wizard != null) {
         _wizard.ProjectItemFinishedGenerating(projectItem);
     }
 }
예제 #20
0
        // The docs say you can't rely on the 'inputFilePath' value, but there's *no other way* to know the base file name or the project!
        public int Generate(
            string inputFilePath,
            string inputFileContents,
            string defaultNamespace,
            IntPtr[] outputFileContents,
            out uint outputByteCount,
            IVsGeneratorProgress progress)
        {
            outputByteCount = 0;
            List <string>             generatedFiles = new List <string>();
            List <EnvDTE.ProjectItem> generatedItems = new List <EnvDTE.ProjectItem>();

            this.InputFilePath     = inputFilePath;
            this.InputFileContents = inputFileContents;
            this.DefaultNamespace  = defaultNamespace;

            this.GetProject();

            foreach (var iter in this.GetIterations())
            {
                try
                {
                    // Get the file for this iteration.
                    // TODO: correct for full/relative paths?
                    string file = this.GetFileName(iter);

                    // Keep track of generated files, we may need to add them to the project.
                    generatedFiles.Add(file);

                    // Create the file...
                    using (FileStream stream = File.Create(file))
                    {
                        byte[] content = this.GenerateContent(iter);

                        stream.Write(content, 0, content.Length);
                        ////stream.Close();
                    }

                    // Ensure the new item is a child of the input file...
                    EnvDTE.ProjectItem childItem = this.ProjectItem.ProjectItems.AddFromFile(file);
                    generatedItems.Add(childItem);
                    this.AdjustChildItem(iter, childItem);
                }
                catch (Exception ex)
                {
                    if (ErrorHandler.IsCriticalException(ex))
                    {
                        throw;
                    }
                }
            }

            // Delete any child items that aren't ours...
            foreach (EnvDTE.ProjectItem childItem in this.ProjectItem.ProjectItems)
            {
                if (!childItem.Name.EndsWith(this.GetDefaultExtension()) &&
                    !generatedItems.Contains(childItem))
                {
                    childItem.Delete();
                }
            }

            // Finally, generate the summary content...
            byte[] summaryContent = this.GenerateSummaryContent();

            if (summaryContent == null || summaryContent.Length == 0)
            {
                outputFileContents[0] = IntPtr.Zero;
                outputByteCount       = 0;
            }
            else
            {
                IntPtr mem = Marshal.AllocCoTaskMem(summaryContent.Length);
                Marshal.Copy(summaryContent, 0, mem, summaryContent.Length);

                outputFileContents[0] = mem;
                outputByteCount       = (uint)summaryContent.Length;
            }

            return(VSConstants.S_OK);
        }
예제 #21
0
        public override string Transform(string fullFileName, string text, EnvDTE.ProjectItem projectItem)
        {
            string result = TransformToCss(fullFileName, text, projectItem);

            return(result);
        }
예제 #22
0
        public override void Process(Manager.VSProjectItemManager manager, string fullFileName, EnvDTE.ProjectItem projectItem, string baseFileName, string outputText)
        {
            base.Process(manager, fullFileName, projectItem, baseFileName, outputText);

            var    mode = this.GetMinifyType(fullFileName);
            string mini = CssEngine.Minify(fullFileName, outputText, projectItem, mode);

            manager.AddFileByFileName(baseFileName + this.Settings.OutputExtensionCSS, mini);
        }
예제 #23
0
 public ORMExtensionManager(EnvDTE.ProjectItem projectItem)
 {
     myProjectItem = projectItem;
 }
예제 #24
0
        /// <summary>
        /// Create an IItemContainer wrapper against IHierarchyNode
        /// </summary>
        internal static IItemContainer CreateItem(IServiceProvider serviceProvider, IHierarchyNode node)
        {
            if (node == null)
            {
                return(null);
            }

            var nestedHiearchy = node.GetObject <IVsHierarchy>();
            var extObject      = node.ExtObject;

            if (nestedHiearchy != null)
            {
                if (nestedHiearchy.GetType().FullName == "Microsoft.VisualStudio.Project.ProjectNode")
                {
                    return(new VsProject(serviceProvider, node));
                }
                else if (nestedHiearchy.GetType().FullName == "Microsoft.VisualStudio.Project.FolderNode")
                {
                    return(new VsFolder(serviceProvider, node));
                }
                else if (nestedHiearchy is VSLangProj.References)
                {
                    return(new VsProjectReference(serviceProvider, node));
                }
            }

            if (extObject != null)
            {
                if (extObject.GetType().FullName == "Microsoft.VisualStudio.Project.Automation.OAProject")
                {
                    return(new VsProject(serviceProvider, node));
                }
                else if (extObject.GetType().FullName == "Microsoft.VisualStudio.Project.Automation.OAFolderItem")
                {
                    return(new VsFolder(serviceProvider, node));
                }
                else if (extObject is EnvDTE.Project)
                {
                    if (((EnvDTE.Project)extObject).Object is EnvDTE80.SolutionFolder)
                    {
                        return(new VsSolutionFolder(serviceProvider, node));
                    }

                    return(new VsProject(serviceProvider, node));
                }
                else if (extObject is EnvDTE.ProjectItem)
                {
                    string kind = null;
                    try
                    {
                        kind = ((EnvDTE.ProjectItem)extObject).Kind;
                    }
                    catch (Exception)
                    {
                        kind = null;
                    }
                    if (kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
                    {
                        return(new VsFolder(serviceProvider, node));
                    }
                    else
                    {
                        EnvDTE.ProjectItem x = (EnvDTE.ProjectItem)extObject;
                        if (x.Object is VSLangProj.References)
                        {
                            return(new VsProjectReferences(serviceProvider, node));
                        }

                        return(new VsItem(serviceProvider, node));
                    }
                }
                else if (extObject is VSLangProj.Reference)
                {
                    return(new VsProjectReference(serviceProvider, node));
                }
                else if (extObject is EnvDTE.Solution)
                {
                    return(new VsSolution(serviceProvider));
                }

                return(new VsUnknownItem(serviceProvider, node));
            }

            return(new VsUnknownItem(serviceProvider, node));
        }
예제 #25
0
        private static bool TryGetFile(EnvDTE.ProjectItems envDTEProjectItems, string name, out EnvDTE.ProjectItem envDTEProjectItem)
        {
            envDTEProjectItem = GetProjectItem(envDTEProjectItems, name, FileKinds);

            if (envDTEProjectItem == null)
            {
                // Try to get the nested project item
                return(TryGetNestedFile(envDTEProjectItems, name, out envDTEProjectItem));
            }

            return(envDTEProjectItem != null);
        }
예제 #26
0
 private void ProjectItemsEvents_ItemRenamed(EnvDTE.ProjectItem ProjectItem, string OldName)
 {
     _clippy.StartAnimation(ClippyAnimations.Writing, true);
 }
예제 #27
0
        /// <summary>
        /// This is called after the single file generator has been invoked to create or update the code file.
        /// </summary>
        /// <param name="fileNode">The node associated to the generator</param>
        /// <param name="data">data to update the file with</param>
        /// <param name="size">size of the data</param>
        /// <param name="fileName">Name of the file to update or create</param>
        /// <returns>full path of the file</returns>
        protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName)
        {
            string filePath             = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName);
            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user?
            if (rdt == null)
            {
                ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL);
            }

            IVsHierarchy hier;
            uint         cookie;
            uint         itemid;
            IntPtr       docData = IntPtr.Zero;

            ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie));
            if (docData != IntPtr.Zero)
            {
                Marshal.Release(docData);
                IVsTextStream srpStream;
                string        inputFileContents = this.GetBufferContents(filePath, out srpStream);
                if (srpStream != null)
                {
                    int oldLen = 0;
                    int hr     = srpStream.GetSize(out oldLen);
                    if (ErrorHandler.Succeeded(hr))
                    {
                        IntPtr dest = IntPtr.Zero;
                        try
                        {
                            dest = Marshal.AllocCoTaskMem(data.Length);
                            Marshal.Copy(data, 0, dest, data.Length);
                            ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2));
                        }
                        finally
                        {
                            if (dest != IntPtr.Zero)
                            {
                                Marshal.Release(dest);
                            }
                        }
                    }
                }
            }
            else
            {
                using (FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    generatedFileStream.Write(data, 0, size);
                    generatedFileStream.SetLength(size);
                }

                EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem;
                if (projectItem != null && (this.projectMgr.FindChild(fileNode.FileName) == null))
                {
                    projectItem.ProjectItems.AddFromFile(filePath);
                }
            }
            return(filePath);
        }
예제 #28
0
 private void ProjectItemsEvents_ItemRemoved(EnvDTE.ProjectItem ProjectItem)
 {
     _clippy.StartAnimation(ClippyAnimations.EmptyTrash, true);
 }
        public ORMGeneratorSelectionControl(EnvDTE.ProjectItem projectItem, IServiceProvider serviceProvider)
            : this()
        {
            _projectItem     = projectItem;
            _serviceProvider = serviceProvider;
#if VISUALSTUDIO_10_0
            ProjectRootElement project         = ProjectRootElement.TryOpen(projectItem.ContainingProject.FullName);
            string             projectFullPath = project.FullPath;
#else // VISUALSTUDIO_10_0
            Project project         = Engine.GlobalEngine.GetLoadedProject(projectItem.ContainingProject.FullName);
            string  projectFullPath = project.FullFileName;
#endif // VISUALSTUDIO_10_0
            _project = project;

            string projectItemRelativePath = (string)projectItem.Properties.Item("LocalPath").Value;
            projectItemRelativePath  = (new Uri(projectFullPath)).MakeRelativeUri(new Uri(projectItemRelativePath)).ToString();
            _projectItemRelativePath = projectItemRelativePath;

#if VISUALSTUDIO_10_0
            ProjectItemGroupElement originalItemGroup = ORMCustomTool.GetItemGroup(project, projectItemRelativePath);
            ProjectItemGroupElement itemGroup;
            if (originalItemGroup == null)
            {
                itemGroup           = project.AddItemGroup();
                itemGroup.Condition = string.Concat(ITEMGROUP_CONDITIONSTART, projectItemRelativePath, ITEMGROUP_CONDITIONEND);
            }
            else
            {
                itemGroup           = project.AddItemGroup();
                itemGroup.Condition = originalItemGroup.Condition;
                foreach (ProjectItemElement item in originalItemGroup.Items)
                {
                    ProjectItemElement newItem = itemGroup.AddItem(item.ItemType, item.Include);
                    newItem.Condition = item.Condition;
                    foreach (ProjectMetadataElement metadataElement in item.Metadata)
                    {
                        newItem.AddMetadata(metadataElement.Name, metadataElement.Value);
                    }
                }
            }
#else // VISUALSTUDIO_10_0
            BuildItemGroup originalItemGroup = ORMCustomTool.GetItemGroup(project, projectItemRelativePath);
            BuildItemGroup itemGroup;
            if (originalItemGroup == null)
            {
                itemGroup           = project.AddNewItemGroup();
                itemGroup.Condition = string.Concat(ITEMGROUP_CONDITIONSTART, projectItemRelativePath, ITEMGROUP_CONDITIONEND);
            }
            else
            {
                itemGroup           = project.AddNewItemGroup();
                itemGroup.Condition = originalItemGroup.Condition;
                foreach (BuildItem item in originalItemGroup)
                {
                    BuildItem newItem = itemGroup.AddNewItem(item.Name, item.Include, false);
                    newItem.Condition = item.Condition;
                    item.CopyCustomMetadataTo(newItem);
                }
            }
#endif // VISUALSTUDIO_10_0
            _originalItemGroup = originalItemGroup;
            _itemGroup         = itemGroup;

            string condition = itemGroup.Condition.Trim();

            string sourceFileName = this._sourceFileName = projectItem.Name;

            this.textBox_ORMFileName.Text = sourceFileName;

            this.button_SaveChanges.Click += new EventHandler(this.SaveChanges);
            this.button_Cancel.Click      += new EventHandler(this.Cancel);

            ITree tree = (ITree)(this.virtualTreeControl.MultiColumnTree = new MultiColumnTree(2));
            this.virtualTreeControl.SetColumnHeaders(new VirtualTreeColumnHeader[]
            {
                // TODO: Localize these.
                new VirtualTreeColumnHeader("Generated File Format", 0.30f, VirtualTreeColumnHeaderStyles.ColumnPositionLocked | VirtualTreeColumnHeaderStyles.DragDisabled),
                new VirtualTreeColumnHeader("Generated File Name", 1f, VirtualTreeColumnHeaderStyles.ColumnPositionLocked | VirtualTreeColumnHeaderStyles.DragDisabled)
            }, true);
            MainBranch mainBranch     = this._mainBranch = new MainBranch(this);
            int        totalCount     = mainBranch.VisibleItemCount;
            int[]      primaryIndices = new int[totalCount];
            for (int i = 0; i < totalCount; ++i)
            {
                if (mainBranch.IsPrimaryDisplayItem(i))
                {
                    primaryIndices[i] = i - totalCount;
                }
                else
                {
                    primaryIndices[i] = i + 1;
                }
            }
            Array.Sort <int>(primaryIndices);
            int lastPrimary = -1;
            for (int i = 0; i < totalCount; ++i)
            {
                int modifiedIndex = primaryIndices[i];
                if (modifiedIndex < 0)
                {
                    primaryIndices[i] = modifiedIndex + totalCount;
                }
                else
                {
                    if (lastPrimary == -1)
                    {
                        lastPrimary = i - 1;
                    }
                    primaryIndices[i] = modifiedIndex - 1;
                }
            }
            int modifierCount = totalCount - mainBranch.Branches.Count;
            tree.Root = (lastPrimary == -1) ? (IBranch)mainBranch : new BranchPartition(
                mainBranch,
                primaryIndices,
                new BranchPartitionSection(0, lastPrimary + 1, null),
                new BranchPartitionSection(totalCount - modifierCount, modifierCount, "Generated File Modifiers"),
                new BranchPartitionSection(lastPrimary + 1, totalCount - lastPrimary - modifierCount - 1, "Intermediate and Secondary Files"));                 // UNDONE: Localize Header
            this.virtualTreeControl.ShowToolTips   = true;
            this.virtualTreeControl.FullCellSelect = true;

#if VISUALSTUDIO_10_0
            Dictionary <string, ProjectItemElement> buildItemsByGenerator = this._itemsByGenerator = new Dictionary <string, ProjectItemElement>(itemGroup.Count, StringComparer.OrdinalIgnoreCase);
            foreach (ProjectItemElement buildItem in itemGroup.Items)
#else // VISUALSTUDIO_10_0
            Dictionary <string, BuildItem> buildItemsByGenerator = this._itemsByGenerator = new Dictionary <string, BuildItem>(itemGroup.Count, StringComparer.OrdinalIgnoreCase);
            foreach (BuildItem buildItem in itemGroup)
#endif // VISUALSTUDIO_10_0
            {
                // Do this very defensively so that the dialog can still be opened if a project is out
                // of step with the generators registered on a specific machine.
                string        generatorNameData = buildItem.GetEvaluatedMetadata(ITEMMETADATA_ORMGENERATOR);
                string[]      generatorNames;            // The first string is the primary generator, others are the format modifiers
                int           generatorNameCount;
                IORMGenerator primaryGenerator;
                MainBranch.OutputFormatBranch primaryFormatBranch;
                if (!String.IsNullOrEmpty(generatorNameData) &&
                    String.Equals(buildItem.GetEvaluatedMetadata(ITEMMETADATA_DEPENDENTUPON), sourceFileName, StringComparison.OrdinalIgnoreCase) &&
                    null != (generatorNames = generatorNameData.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)) &&
                    0 != (generatorNameCount = generatorNames.Length) &&
                    ORMCustomTool.ORMGenerators.TryGetValue(generatorNames[0], out primaryGenerator) &&
                    mainBranch.Branches.TryGetValue(primaryGenerator.ProvidesOutputFormat, out primaryFormatBranch))
                {
                    System.Diagnostics.Debug.Assert(primaryFormatBranch.SelectedORMGenerator == null);
                    primaryFormatBranch.SelectedORMGenerator = primaryGenerator;
                    buildItemsByGenerator.Add(generatorNames[0], buildItem);

                    // Format modifiers are attached to the end of the list
                    for (int i = 1; i < generatorNameCount; ++i)
                    {
                        MainBranch.OutputFormatBranch modifierBranch = primaryFormatBranch.NextModifier;
                        string findName = generatorNames[i];
                        while (modifierBranch != null)
                        {
                            IORMGenerator testGenerator = modifierBranch.ORMGenerators[0];
                            if (testGenerator.OfficialName == findName)
                            {
                                modifierBranch.SelectedORMGenerator = testGenerator;
                                break;
                            }
                            modifierBranch = modifierBranch.NextModifier;
                        }
                    }
                }
            }
        }
예제 #30
0
 private void ProjectItemsEvents_ItemAdded(EnvDTE.ProjectItem ProjectItem)
 {
     _clippy.StartAnimation(ClippyAnimations.Congratulate, true);
 }
예제 #31
0
        public static void SetCustomTool(this EnvDTE.ProjectItem projectItem, string value)
        {
            Contract.Requires(projectItem != null);

            SetProperty(projectItem, @"CustomTool", value);
        }
예제 #32
0
        private void AddProjectItems([NotNull] EnvDTE.ProjectItem projectItem, [NotNull] JObject jParentItem)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            if (projectItem.Object is VSLangProj.References) // MPF project (e.g. WiX) references folder, do not traverse...
            {
                return;
            }

            if (projectItem.Properties == null)
            {
                return;
            }

            var jProjectItem = new JObject();

            foreach (var property in projectItem.Properties.OfType <EnvDTE.Property>().OrderBy(item => item.Name))
            {
                var propertyName = "<unknown>";
                try
                {
                    propertyName = property.Name;

                    var ignored = new[] { "{", "Date", "File", "Extender", "LocalPath", "URL", "Identity", "BuildAction", "SubType", "HTMLTitle", "ModifiedBy", "__id", "Author" };
                    if (ignored.Any(prefix => propertyName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    // exclude properties with their default values:
                    var propertyValue = property.Value;
                    if (propertyValue == null)
                    {
                        continue;
                    }
                    if (propertyValue is string stringValue && string.IsNullOrEmpty(stringValue))
                    {
                        continue;
                    }
                    if (propertyValue is bool booleanValue && !booleanValue)
                    {
                        continue;
                    }
                    if (((propertyName == "Link") || (propertyName == "FolderName")) &&
                        string.Equals(projectItem.Name, propertyValue as string, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    jProjectItem.Add(propertyName, JToken.FromObject(propertyValue));
                }
                catch (NotImplementedException)
                {
                    // Just ignore...
                }
                catch (Exception ex)
                {
                    _tracer.TraceWarning("Can't read property {0}: {1}", propertyName, ex.Message);
                }
            }

            jParentItem.Add(projectItem.Name, jProjectItem);

            AddProjectItems(projectItem.ProjectItems, jProjectItem);

            if (projectItem.SubProject != null)
            {
                AddProjectItems(projectItem.SubProject.ProjectItems, jProjectItem);
            }
        }
예제 #33
0
 public void BeforeOpeningFile(ProjectItem projectItem)
 {
     AssertWizard();
     _wizard?.BeforeOpeningFile(projectItem);
 }
예제 #34
0
        private static bool TryGetFolder(EnvDTE.ProjectItems envDTEProjectItems, string name, out EnvDTE.ProjectItem envDTEProjectItem)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            envDTEProjectItem = GetProjectItem(envDTEProjectItems, name, FolderKinds);

            return(envDTEProjectItem != null);
        }
예제 #35
0
 public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #36
0
        private static bool TryGetFile(EnvDTE.ProjectItems envDTEProjectItems, string name, out EnvDTE.ProjectItem envDTEProjectItem)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            envDTEProjectItem = GetProjectItem(envDTEProjectItems, name, FileKinds);

            if (envDTEProjectItem == null)
            {
                // Try to get the nested project item
                return(TryGetNestedFile(envDTEProjectItems, name, out envDTEProjectItem));
            }

            return(envDTEProjectItem != null);
        }
예제 #37
0
 public void BeforeOpeningFile(ProjectItem projectItem) {
     if (_wizard != null) {
         _wizard.BeforeOpeningFile(projectItem);
     }
 }
예제 #38
0
		private void InitializeTool()
		{
			mOutLog = null;
			mProjItem = (EnvDTE.ProjectItem)GetService(typeof(EnvDTE.ProjectItem));
			
			string tooln = "eBayWebServiceGenerator";
			if (mProjItem == null || mProjItem.Name == String.Empty)
			{
				tooln = "eBayWebServiceGenerator";
			}
			else 
			{
				tooln = mProjItem.Name;

				EnvDTE.Window win = mProjItem.DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
				EnvDTE.OutputWindow ow = (EnvDTE.OutputWindow) win.Object;
				foreach (EnvDTE.OutputWindowPane owPane in ow.OutputWindowPanes)
				{
					if (owPane.Name == tooln)
					{
						mOutLog = owPane;
						break;
					}
				}
		
				if (mOutLog == null)
				{
					mOutLog = ow.OutputWindowPanes.Add(tooln);
				}
				mOutLog.Activate();
			}
		}
예제 #39
0
 public void BeforeOpeningFile(ProjectItem projectItem) { }
예제 #40
0
        /// <summary>
        /// Ensure that the current project item has the required extensions loaded.
        /// This is only called after verifying that the current project item does
        /// not satisfy the requirements.
        /// </summary>
        /// <param name="projectItem">The <see cref="EnvDTE.ProjectItem"/> to modify</param>
        /// <param name="serviceProvider">The <see cref="IServiceProvider"/> for document tracking.</param>
        /// <param name="extensions">An <see cref="T:ICollection{System.String}"/> of additional required extensions</param>
        public static bool EnsureExtensions(EnvDTE.ProjectItem projectItem, IServiceProvider serviceProvider, ICollection <string> extensions)
        {
            ServiceProvider provider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)projectItem.DTE);

            // UNDONE: Localize message strings in here
            if ((int)DialogResult.No == VsShellUtilities.ShowMessageBox(
                    provider,
                    "Additional extensions are required to support the chosen generators. Would you like to load the required extensions now?",
                    "ORM Generator Selection",
                    OLEMSGICON.OLEMSGICON_QUERY,
                    OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST))
            {
                return(false);
            }
            EnvDTE.Document document    = projectItem.Document;
            bool            secondPass  = false;
            bool            tryDocument = true;
            string          itemPath    = null;

            while (tryDocument)
            {
                object     documentExtensionManager;
                MethodInfo methodInfo;
                if (null != document &&
                    null != (documentExtensionManager = ORMCustomToolUtility.GetDocumentExtension <object>(document, "ORMExtensionManager", itemPath ?? (itemPath = projectItem.get_FileNames(0)), serviceProvider)) &&
                    null != (methodInfo = documentExtensionManager.GetType().GetMethod("EnsureExtensions", new Type[] { typeof(string[]) })))
                {
                    string[] extensionsArray = new string[extensions.Count];
                    extensions.CopyTo(extensionsArray, 0);
                    methodInfo.Invoke(documentExtensionManager, new object[] { extensionsArray });
                    return(true);
                }

                if (secondPass)
                {
                    return(false);
                }
                tryDocument = false;
                secondPass  = true;

                // UNDONE: Localize message strings in here
                if ((int)DialogResult.No == VsShellUtilities.ShowMessageBox(
                        provider,
                        "The .ORM file must be open in the default designer to add extensions. Would you like to open or reopen the document now?",
                        "ORM Generator Selection",
                        OLEMSGICON.OLEMSGICON_QUERY,
                        OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST))
                {
                    return(false);
                }

                if (document != null)
                {
                    document.Close(EnvDTE.vsSaveChanges.vsSaveChangesPrompt);
                    document = projectItem.Document;
                }
                if (document == null)
                {
                    projectItem.Open(Guid.Empty.ToString("B")).Visible = true;
                    document    = projectItem.Document;
                    tryDocument = true;
                }
            }
            return(false);
        }
예제 #41
0
파일: frmMain.cs 프로젝트: japj/bidshelper
        public MainForm(Cube selectedCube, EnvDTE.ProjectItem projectItm)
        {
            this.realCube = selectedCube;

            //easiest way to allow changes in this window to be made so they can still be rolled back by the cancel button so they don't show up in BIDS
            this.cloneDB = selectedCube.Parent.Clone();

            InitializeComponent();
            mProjItem = projectItm;
            TreeNode nd;
            nd = CreateStaticNode(treeView1.Nodes, selectedCube.Name, cloneDB.Cubes[selectedCube.ID], ImgListMetadataCubeIndex);
            nd.Expand();
            nd = CreateNode(nd.Nodes, TagMeasureGroups, TagMeasureGroups, ImgListMetadataFolderIndex);
            nd.Expand();
        }
 public LuaInterface(FrameXmlDesignerLoader designerLoader)
 {
     this.DesignerLoader = designerLoader;
     firstChildItem = LoadFile();
 }