Example #1
0
        public override DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            try
            {
                var relativePath = PackageUtilities.MakeRelative(_scriptFile.FullName, _targetFileName)
                                   .Replace("\\", "/");
                string insertString = null;
                switch (Path.GetExtension(relativePath))
                {
                case ".cake":
                    insertString = $"#load \"{relativePath}\"";
                    break;

                case ".dll":
                    insertString = $"#r \"{relativePath}\"";
                    break;
                }

                using (var edit = _textView.TextBuffer.CreateEdit())
                {
                    edit.Insert(GetInsertPosition(), insertString + Environment.NewLine);
                    edit.Apply();
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(DragDropPointerEffects.Copy);
        }
Example #2
0
        public static string GetFileNameSpace(Project project, string filePath)
        {
            var relative = PackageUtilities.MakeRelative(project.GetRootFolder(), Path.GetDirectoryName(filePath));
            var rootNs   = project.GetRootNamespace();

            return($"{rootNs}.{CleanNameSpace(relative)}".TrimEnd('.'));
        }
Example #3
0
        public static async Task <string> GetTemplateFilePathAsync(Project project, string file)
        {
            var extension = Path.GetExtension(file).ToLowerInvariant();
            var name      = Path.GetFileName(file);
            var safeName  = name.StartsWith(".") ? name : Path.GetFileNameWithoutExtension(file);
            var relative  = PackageUtilities.MakeRelative(project.GetRootFolder(), Path.GetDirectoryName(file) ?? "");

            string templateFile = null;
            var    list         = _templateFiles.ToList();

            AddTemplatesFromCurrentFolder(list, Path.GetDirectoryName(file));

            // Look for direct file name matches
            if (list.Any(f => Path.GetFileName(f).Equals(name + _defaultExt, StringComparison.OrdinalIgnoreCase)))
            {
                var tmplFile = list.FirstOrDefault(f => Path.GetFileName(f).Equals(name + _defaultExt, StringComparison.OrdinalIgnoreCase));
                templateFile = Path.Combine(Path.GetDirectoryName(tmplFile), name + _defaultExt);//GetTemplate(name);
            }

            // Look for file extension matches
            else if (list.Any(f => Path.GetFileName(f).Equals(extension + _defaultExt, StringComparison.OrdinalIgnoreCase)))
            {
                var tmplFile = list.FirstOrDefault(f => Path.GetFileName(f).Equals(extension + _defaultExt, StringComparison.OrdinalIgnoreCase));
                var tmpl     = AdjustForSpecific(safeName, extension);
                templateFile = Path.Combine(Path.GetDirectoryName(tmplFile), tmpl + _defaultExt); //GetTemplate(tmpl);
            }

            var template = await ReplaceTokensAsync(project, safeName, relative, templateFile);

            return(NormalizeLineEndings(template));
        }
Example #4
0
        public static async Task <string> GetTemplateFilePathAsync(Project project, string file)
        {
            string extension = Path.GetExtension(file).ToLowerInvariant();
            string name      = Path.GetFileName(file);
            string safeName  = name.StartsWith(".") ? name : Path.GetFileNameWithoutExtension(file);
            string relative  = PackageUtilities.MakeRelative(project.GetRootFolder(), Path.GetDirectoryName(file));

            string templateFile = null;

            // Look for direct file name matches
            if (_templateFiles.Any(f => Path.GetFileName(f).Equals(name + _defaultExt, StringComparison.OrdinalIgnoreCase)))
            {
                templateFile = GetTemplate(name);
            }

            // Look for file extension matches
            else if (_templateFiles.Any(f => Path.GetFileName(f).Equals(extension + _defaultExt, StringComparison.OrdinalIgnoreCase)))
            {
                string tmpl = AdjustForSpecific(safeName, extension);
                templateFile = GetTemplate(tmpl);
            }

            string template = await ReplaceTokensAsync(project, safeName, relative, templateFile);

            return(NormalizeLineEndings(template));
        }
Example #5
0
        /// <summary>
        /// Make the given path relative to the project file.
        /// </summary>
        protected internal string MakeProjectRelative(string filename)
        {
            string projectPath;

            ErrorHandler.ThrowOnFailure(ProjectMgr.GetCanonicalName((uint)VSConstants.VSITEMID.Root, out projectPath));
            // Try to use common prefix to avoid upper/lower differences.
            var i   = 0;
            var max = Math.Min(filename.Length, projectPath.Length);

            while (i < max)
            {
                if (char.ToUpper(filename[i]) != char.ToUpper(projectPath[i]))
                {
                    break;
                }
                i++;
            }
            if (i > 0)
            {
                projectPath = filename.Substring(0, i) + projectPath.Substring(i);
            }
            var result = PackageUtilities.MakeRelative(projectPath, filename);

            return(result);
        }
Example #6
0
        public static async Task <string> GetTemplateFilePathAsync(Project project, string file, TemplateType templateType, string inputCamel)
        {
            string name     = Path.GetFileName(file);
            string safeName = name.StartsWith(".") ? name : Path.GetFileNameWithoutExtension(file);
            string relative = PackageUtilities.MakeRelative(project.GetRootFolder(), Path.GetDirectoryName(file));

            string templateFile = _templateFiles.FirstOrDefault(f => Path.GetFileName(f).Equals(templateType + _defaultExt, StringComparison.OrdinalIgnoreCase));

            string template = await ReplaceTokensAsync(project, safeName, relative, templateFile, templateType, inputCamel);

            return(NormalizeLineEndings(template));
        }
Example #7
0
        public static async Task <TemplateInfo> GetTemplateInfoAsync(Project project, string file)
        {
            TemplateInfo result    = new TemplateInfo();
            string       extension = Path.GetExtension(file).ToLowerInvariant();
            string       name      = Path.GetFileName(file);
            string       safeName  = name.StartsWith(".") ? name : Path.GetFileNameWithoutExtension(file);
            string       relative  = PackageUtilities.MakeRelative(project.GetRootFolder(), Path.GetDirectoryName(file));
            string       folder    = Path.GetDirectoryName(file);

            string localTemplate = SearchForLocalTemplate(Path.GetDirectoryName(file), relative, _localTemplateSearchDepth);

            result.IsLocal = !string.IsNullOrEmpty(localTemplate);

            string templateFullName = null;

            if (name == AddAnyFilePackage.Dummy)
            {
            }
            // Look for the local template
            else if (result.IsLocal)
            {
                templateFullName = localTemplate;
            }
            else
            {
                // Look for direct file name matches
                if (_templateFiles.Any(f => Path.GetFileName(f).Equals(name + _defaultExt, StringComparison.OrdinalIgnoreCase)))
                {
                    templateFullName = GetTemplate(name);
                }

                // Look for file extension matches
                else if (_templateFiles.Any(f => Path.GetFileName(f).Equals(extension + _defaultExt, StringComparison.OrdinalIgnoreCase)))
                {
                    string tmpl = AdjustForSpecific(safeName, extension);
                    templateFullName = GetTemplate(tmpl);
                }
            }

            if (name != AddAnyFilePackage.Dummy)
            {
                result.Extension = string.IsNullOrEmpty(extension) ? _csExt : extension;
            }

            HandleItemName(safeName, templateFullName, result);
            result.WritePath = result.IsLocal? Path.Combine(folder, result.LongItemName + result.Extension) : file;
            string templateContent = await ReplaceTokensAsync(project, result, relative, templateFullName);

            result.TemplateFullName = templateFullName;
            result.Content          = NormalizeLineEndings(templateContent);
            return(result);
        }
        /// <summary>
        /// Adds a file to the MSBuild project with metadata where appropriate
        /// </summary>
        /// <param name="file">The file to be added</param>
        /// <returns>A ProjectElement describing the newly added file</returns>
        /// <remarks>Appropriate metadata is added based on the file's extension</remarks>
        protected internal override ProjectElement AddFileToMsBuild(string file)
        {
            SandcastleBuildAction buildAction = SandcastleProject.DefaultBuildAction(file);
            string itemPath = PackageUtilities.MakeRelative(base.FileName, file);

            ProjectElement newItem = this.CreateMsBuildFileItem(itemPath, buildAction.ToString());

            // Set the default ID and alternate text if it is an Image element
            if (buildAction == SandcastleBuildAction.Image)
            {
                newItem.SetImageMetadata();
            }

            return(newItem);
        }
        private void UpdateTextBuffer(string fileName, string relativeTo)
        {
            int    position = _view.Caret.Position.BufferPosition.Position;
            string relative = PackageUtilities.MakeRelative(relativeTo, fileName)
                              .Replace("\\", "/");

            string altText = fileName.ToFriendlyName();
            string image   = string.Format(CultureInfo.InvariantCulture, _format, relative, altText);

            using (var edit = _view.TextBuffer.CreateEdit())
            {
                edit.Insert(position, image);
                edit.Apply();
            }
        }
Example #10
0
        private bool TryGenerateManifest(Project project, string fileName)
        {
            if (project == null)
            {
                return(false);
            }

            try
            {
                string assembly = Assembly.GetExecutingAssembly().Location;
                string root     = Path.GetDirectoryName(assembly);
                string toolsDir = Path.Combine(root, "ImageManifest\\Tools");

                string images       = string.Join(";", _selectedFiles.Select(f => PackageUtilities.MakeRelative(fileName, f)));
                string assemblyName = project.Properties.Item("AssemblyName").Value.ToString();
                string manifestName = Path.GetFileName(fileName);

                string args = $"/manifest:\"{manifestName}\" /resources:\"{images}\" /assembly:{assemblyName} /guidName:{Path.GetFileNameWithoutExtension(fileName)}Guid /rootPath:\"{project.GetRootFolder()}\\\"";

                var start = new ProcessStartInfo
                {
                    WorkingDirectory = Path.GetDirectoryName(fileName),
                    CreateNoWindow   = true,
                    UseShellExecute  = false,
                    FileName         = Path.Combine(toolsDir, "ManifestFromResources.exe"),
                    Arguments        = args
                };

                using (var p = new System.Diagnostics.Process())
                {
                    p.StartInfo = start;
                    p.Start();
                    p.WaitForExit();
                }

                return(File.Exists(fileName));
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }

            return(false);
        }
Example #11
0
        /// <summary>
        /// Links a reference node to the project and hierarchy.
        /// </summary>
        public override void BindReferenceData()
        {
            // BindReferenceData only happens for newly created AssemblyReferenceNodes (as opposed to loaded from fsproj)
            Debug.Assert(this.resolvedInfo.WasSuccessfullyResolved, "assembly was not resolved, we should not be trying to link a node to put in .fsproj file");

            // Logic here follows that of
            // \\ddindex2\sources_tfs\Dev10_Main\vsproject\langbuild\langref.cpp
            // AddMSBuildItem()

            this.ItemNode = new ProjectElement(this.ProjectMgr, this.msbuildProjectionInfo.WantFusionName ? this.resolvedInfo.AssemblyName.FullName : this.resolvedInfo.AssemblyName.Name, ProjectFileConstants.Reference);

            if (this.msbuildProjectionInfo.WantSpecificVersion != null)
            {
                if (this.msbuildProjectionInfo.WantSpecificVersion.Value)
                {
                    // Note that we should never set <SpecificVersion>True from
                    // UI 'add reference', as it breaks multi-targeting.  User must manually
                    // opt in to changing SV to get 'true' if desired.
                }
                else
                {
                    if (this.msbuildProjectionInfo.WantFusionName)
                    {
                        this.ItemNode.SetMetadata(ProjectFileConstants.SpecificVersion, "False");
                    }
                }
            }
            if (this.resolvedInfo.IsNoPIA)
            {
                this.ItemNode.SetMetadata(ProjectFileConstants.EmbedInteropTypes, "True");
            }
            if (this.msbuildProjectionInfo.WantHintPath)
            {
                this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, PackageUtilities.MakeRelative(this.ProjectMgr.ProjectFolder + "\\", this.myAssemblyPath));
            }
            if (this.resolvedInfo.CopyLocalDefault)
            {
                // In fact this is only set if CopyLocal 'is overridden', which is only as a result of explicit user action (or automation).
                // So simply 'add reference' should never set the metadata value ProjectFileConstants.Private
            }
            // TODO - Note that we don't currently support any logic for
            // LBXML_KEY_REFERENCE_ALIAS           "Name"
            // LBXML_KEY_REFERENCE_EXTENSION       "ExecutableExtension"
        }
        public override void Execute(CancellationToken cancellationToken)
        {
            string fileName;
            string dir = Path.GetDirectoryName(_file);

            if (!TryGetFileName(dir, out fileName))
            {
                return;
            }

            string relative = PackageUtilities.MakeRelative(_file, fileName).Replace("\\", "/");

            string text = string.Format(_format, _span.GetText(), Uri.EscapeUriString(relative));

            using (var edit = _span.Snapshot.TextBuffer.CreateEdit())
            {
                edit.Replace(_span, text);
                edit.Apply();
            }
        }
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            var    position = dragDropInfo.VirtualBufferPosition.Position;
            var    line     = _view.GetTextViewLineContainingBufferPosition(position);
            string text     = PackageUtilities.MakeRelative(_documentFileName, _draggedFileName)
                              .Replace("\\", "/");

            // Insert a new line if dragged after existing text
            if (line.Start < position)
            {
                text = Environment.NewLine + text;
            }

            using (var edit = _view.TextBuffer.CreateEdit())
            {
                edit.Insert(position, text);
                edit.Apply();
            }

            return(DragDropPointerEffects.Copy);
        }
        private void CreateInheritance(string parentFileName, int padding)
        {
            Dispatcher.VerifyAccess();

            string fileName = _adornmentLayer.TextView.TextBuffer.GetFileName();

            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            string shortcut = GetShortcut();

            if (!string.IsNullOrEmpty(shortcut))
            {
                ToolTip = $"Navigate to immediate parent ({shortcut})";
            }

            string relative = PackageUtilities.MakeRelative(fileName, parentFileName);

            var inherits = new ThemedTextBlock()
            {
                Text     = ("└─  " + relative).PadLeft(relative.Length + 4 + padding),// "→ " + relative,
                FontSize = 16,
                Cursor   = Cursors.Hand,
                ToolTip  = "Click to open " + parentFileName,
                Margin   = new System.Windows.Thickness(0, 3, 0, 0),
            };

            inherits.MouseLeftButtonDown += (s, e) =>
            {
                Dispatcher.VerifyAccess();

                e.Handled = true;
                VsHelpers.PreviewDocument(parentFileName);
                Telemetry.TrackUserTask("InheritanceNavigated");
            };

            Children.Add(inherits);
        }
Example #15
0
        private async void ExecuteAsync(object sender, EventArgs e)
        {
            Telemetry.TrackUserTask("installdialogopened");

            CancellationToken token      = CancellationToken.None;
            Project           project    = VsHelpers.DTE.SelectedItems.Item(1).ProjectItem.ContainingProject;
            string            rootFolder = project.GetRootFolder();

            string   configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName);
            var      dependencies   = Dependencies.FromConfigFile(configFilePath);
            Manifest manifest       = await Manifest.FromFileAsync(configFilePath, dependencies, token);

            string itemFolder               = VsHelpers.DTE.SelectedItems.Item(1).ProjectItem.Properties.Item("FullPath").Value.ToString();
            string relativeFolder           = PackageUtilities.MakeRelative(rootFolder, itemFolder).Replace(Path.DirectorySeparatorChar, '/').Trim('/');
            ILibraryInstallationState state = GetLibraryToInstall(relativeFolder);

            manifest.AddLibrary(state);
            await manifest.SaveAsync(configFilePath, token);

            project.AddFileToProject(configFilePath);
            await LibraryHelpers.RestoreAsync(configFilePath);
        }
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            try
            {
                var    position = dragDropInfo.VirtualBufferPosition.Position;
                string relative = PackageUtilities.MakeRelative(_documentFileName, _draggedFileName)
                                  .Replace("\\", "/");

                string altText = _draggedFileName.ToFriendlyName();
                string image   = string.Format(_markdownTemplate, altText, relative);

                using (var edit = _view.TextBuffer.CreateEdit())
                {
                    edit.Insert(position, image);
                    edit.Apply();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }

            return(DragDropPointerEffects.Copy);
        }
Example #17
0
        private void ValidateSections()
        {
            IEnumerable <EditorConfigDocument> parents = GetAllParentDocuments();

            foreach (Section section in _document.Sections)
            {
                IEnumerable <Section> parentSections = parents.SelectMany(d => d.Sections).Where(s => s.Item.Text == section.Item.Text);

                foreach (Property property in section.Properties)
                {
                    ValidateProperty(property);

                    if (!property.IsValid)
                    {
                        continue;
                    }

                    ErrorCatalog.RootInSection.Run(property.Keyword, (e) =>
                    {
                        if (property.Keyword.Text.Is(SchemaCatalog.Root))
                        {
                            e.Register();
                        }
                    });

                    ErrorCatalog.DuplicateProperty.Run(property.Keyword, (e) =>
                    {
                        if (section.Properties.Last(p => p.Keyword.Text.Is(property.Keyword.Text)) != property)
                        {
                            e.Register();
                        }
                    });

                    ErrorCatalog.ParentDuplicateProperty.Run(property.Keyword, (e) =>
                    {
                        if (!property.Keyword.Errors.Any() && parentSections.Any())
                        {
                            IEnumerable <Property> parentProperties = parentSections.SelectMany(s => s.Properties.Where(p => p.ToString() == property.ToString()));
                            if (parentProperties.Any())
                            {
                                string fileName = PackageUtilities.MakeRelative(_document.FileName, parentProperties.First().Keyword.Document.FileName);
                                e.Register(fileName);
                            }
                        }
                    });

                    ErrorCatalog.TabWidthUnneeded.Run(property.Keyword, property.Keyword.Text.Is("tab_width"), (e) =>
                    {
                        bool hasIndentSize = section.Properties.Any(p => p.IsValid && p.Keyword.Text.Is("indent_size") && p.Value.Text.Is(property.Value.Text));
                        if (hasIndentSize)
                        {
                            e.Register();
                        }
                    });

                    ErrorCatalog.IndentSizeUnneeded.Run(property.Keyword, (e) =>
                    {
                        if (property.Keyword.Text.Is("indent_style") && property.Value.Text.Is("tab"))
                        {
                            IEnumerable <Property> indentSizes = section.Properties.Where(p => p.IsValid && p.Keyword.Text.Is("indent_size"));

                            foreach (Property indentSize in indentSizes)
                            {
                                e.Register(indentSize.Keyword);
                            }
                        }
                    });
                }

                ErrorCatalog.SectionSyntaxError.Run(section.Item, (e) =>
                {
                    if (!section.Item.Text.StartsWith("[") || !section.Item.Text.EndsWith("]"))
                    {
                        e.Register();
                    }
                });

                ErrorCatalog.SpaceInSection.Run(section.Item, (e) =>
                {
                    if (section.Item.Text.Contains(" "))
                    {
                        e.Register();
                    }
                });

                ErrorCatalog.DuplicateSection.Run(section.Item, (e) =>
                {
                    if (_document.Sections.First(s => s.Item.Text == section.Item.Text) != section)
                    {
                        e.Register(section.Item.Text);
                    }
                });

                ErrorCatalog.GlobbingNoMatch.Run(section.Item, !section.Item.HasErrors, (e) =>
                {
                    if (!_globbingCache.ContainsKey(section.Item.Text))
                    {
                        _globbingCache[section.Item.Text] = DoesFilesMatch(Path.GetDirectoryName(_document.FileName), section.Item.Text);
                    }

                    if (!_globbingCache[section.Item.Text])
                    {
                        e.Register(section.Item.Text);
                    }
                });
            }
        }