Example #1
0
        public async Task <AnalyzerOutput> GetXamlAsync(IAsyncServiceProvider serviceProvider)
        {
            AnalyzerOutput result = null;

            if (AnalyzerBase.GetSettings().Profiles.Any())
            {
                var dte = await serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;

                var activeDocument = dte.ActiveDocument;

                var textView = await GetTextViewAsync(serviceProvider);

                var selection = textView.Selection;

                bool isSelection = selection.Start.Position != selection.End.Position;

                var caretPosition = textView.Caret.Position.BufferPosition;

                var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

                var semanticModel = await document.GetSemanticModelAsync();

                var vs         = new VisualStudioAbstraction(this.Logger, this.ServiceProvider, dte);
                var xamlIndent = await vs.GetXamlIndentAsync();

                IDocumentAnalyzer analyzer = null;

                if (activeDocument.Language == "CSharp")
                {
                    analyzer = new CSharpAnalyzer(this.Logger);
                }
                else if (activeDocument.Language == "Basic")
                {
                    analyzer = new VisualBasicAnalyzer(this.Logger);
                }

                result = isSelection
                    ? analyzer?.GetSelectionOutput(await document.GetSyntaxRootAsync(), semanticModel, selection.Start.Position, selection.End.Position, xamlIndent)
                    : analyzer?.GetSingleItemOutput(await document.GetSyntaxRootAsync(), semanticModel, caretPosition.Position, xamlIndent);
            }
            else
            {
                await ShowStatusBarMessageAsync(serviceProvider, StringRes.UI_NoXamlCopiedNoProfilesConfigured);
            }

            return(result);
        }
Example #2
0
        public AnalyzerOutput GetXaml(IAsyncServiceProvider serviceProvider)
        {
            AnalyzerOutput result = null;

            if (AnalyzerBase.GetSettings().Profiles.Any())
            {
                var dte            = (EnvDTE.DTE)serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE)).Result;
                var activeDocument = dte.ActiveDocument;

                var textView = GetTextView(serviceProvider);

                var selection = textView.Selection;

                bool isSelection = selection.Start.Position != selection.End.Position;

                var caretPosition = textView.Caret.Position.BufferPosition;

                var document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

                var semanticModel = document.GetSemanticModelAsync().Result;

                IDocumentAnalyzer analyzer = null;

                if (activeDocument.Language == "CSharp")
                {
                    analyzer = new CSharpAnalyzer(this.Logger);
                }
                else if (activeDocument.Language == "Basic")
                {
                    analyzer = new VisualBasicAnalyzer(this.Logger);
                }

                result = isSelection
                    ? analyzer?.GetSelectionOutput(document.GetSyntaxRootAsync().Result, semanticModel, selection.Start.Position, selection.End.Position)
                    : analyzer?.GetSingleItemOutput(document.GetSyntaxRootAsync().Result, semanticModel, caretPosition.Position);
            }
            else
            {
                ShowStatusBarMessage(serviceProvider, "No XAML copied. No profiles configured.");
            }

            return(result);
        }
Example #3
0
        public async Task ExecuteAsync(string selectedFileName)
        {
            var vmProj = this.vs.GetActiveProject();

            var fileExt      = this.fileSystem.GetFileExtension(selectedFileName);
            var fileContents = this.fileSystem.GetAllFileText(selectedFileName);

            (var syntaxTree, var semModel) = await this.vs.GetDocumentModelsAsync(selectedFileName);

            AnalyzerBase analyzer      = null;
            var          codeBehindExt = string.Empty;

            switch (fileExt)
            {
            case ".cs":
                analyzer      = new CSharpAnalyzer(this.logger);
                codeBehindExt = ((CSharpAnalyzer)analyzer).FileExtension;
                break;

            case ".vb":
                analyzer      = new VisualBasicAnalyzer(this.logger);
                codeBehindExt = ((VisualBasicAnalyzer)analyzer).FileExtension;
                break;
            }

            this.CreateView = false;

            if (analyzer != null)
            {
                var indent = await this.vs.GetXamlIndentAsync();

                // IndexOf is allowing for "class " in C# and "Class " in VB
                var analyzerOutput = ((IDocumentAnalyzer)analyzer).GetSingleItemOutput(await syntaxTree.GetRootAsync(), semModel, fileContents.IndexOf("lass "), indent, this.profile);

                var config = this.profile.ViewGeneration;

                var vmClassName = analyzerOutput.Name;

                var baseClassName = vmClassName;

                if (vmClassName.EndsWith(config.ViewModelFileSuffix))
                {
                    baseClassName = vmClassName.Substring(0, vmClassName.LastIndexOf(config.ViewModelFileSuffix, StringComparison.InvariantCulture));
                }

                var viewClassName = $"{baseClassName}{config.XamlFileSuffix}";

                var    vmProjName = vmProj.Name;
                string viewProjName;

                this.ViewProject = null;

                if (config.AllInSameProject)
                {
                    this.ViewProject = vmProj;
                    viewProjName     = this.ViewProject.Name;
                }
                else
                {
                    var expectedViewProjectName = vmProjName.Replace(config.ViewModelProjectSuffix, config.XamlProjectSuffix);

                    this.ViewProject = this.vs.GetProject(expectedViewProjectName);

                    if (this.ViewProject == null)
                    {
                        this.logger.RecordError(StringRes.Error_UnableToFindProjectInSolution.WithParams(expectedViewProjectName));
                    }

                    viewProjName = this.ViewProject?.Name;
                }

                if (this.ViewProject != null)
                {
                    var folder = this.fileSystem.GetDirectoryName(this.ViewProject.FileName);

                    this.ViewFolder = this.fileSystem.PathCombine(folder, config.XamlFileDirectoryName);

                    // We assume that the type name matches the file name.
                    this.XamlFileName = this.fileSystem.PathCombine(this.ViewFolder, $"{viewClassName}.xaml");
                    this.CodeFileName = this.fileSystem.PathCombine(this.ViewFolder, $"{viewClassName}.xaml.{codeBehindExt}");

                    if (this.fileSystem.FileExists(this.XamlFileName))
                    {
                        this.logger.RecordInfo(StringRes.Info_FileExists.WithParams(this.XamlFileName));

                        var overwrite = this.vs.UserConfirms(StringRes.Prompt_FileExistsTitle, StringRes.Propt_FileExistsMessage);

                        if (overwrite)
                        {
                            this.CreateView = true;
                            this.logger.RecordInfo(StringRes.Info_OverwritingFile.WithParams(this.XamlFileName));
                        }
                        else
                        {
                            this.logger.RecordInfo(StringRes.Info_NotOverwritingFile.WithParams(this.XamlFileName));
                        }
                    }
                    else
                    {
                        this.CreateView = true;
                    }

                    if (this.CreateView)
                    {
                        // Allow for different namespace conventions
                        var viewNamespace = analyzer is CSharpAnalyzer
                                          ? $"{viewProjName}.{config.XamlFileDirectoryName}".TrimEnd('.')
                                          : $"{config.XamlFileDirectoryName}".TrimEnd('.');

                        var vmNamespace = $"{vmProjName}.{config.ViewModelDirectoryName}".TrimEnd('.');

                        var replacementValues = (viewProjName, viewNamespace, vmNamespace, viewClassName, vmClassName);

                        this.XamlFileContents = this.ReplacePlaceholders(config.XamlPlaceholder, replacementValues);

                        var formattedXaml = analyzerOutput.Output.FormatXaml(indent);

                        var placeholderPos         = this.XamlFileContents.IndexOf(Placeholder.GeneratedXAML);
                        var startOfPlaceholderLine = this.XamlFileContents.Substring(0, placeholderPos).LastIndexOf(Environment.NewLine);

                        var insertIndent = placeholderPos - startOfPlaceholderLine - Environment.NewLine.Length;

                        this.XamlFileContents = this.XamlFileContents.Replace(Placeholder.GeneratedXAML, formattedXaml.Replace(Environment.NewLine, Environment.NewLine + new string(' ', insertIndent)).Trim());

                        this.CodeFileContents = this.ReplacePlaceholders(config.CodePlaceholder, replacementValues);
                    }
                }
            }
        }
Example #4
0
        public void Execute(string selectedFileName)
        {
            var vmProj = this.vs.GetActiveProject();

            var fileExt      = this.fileSystem.GetFileExtension(selectedFileName);
            var fileContents = this.fileSystem.GetAllFileText(selectedFileName);

            (var syntaxTree, var semModel) = this.vs.GetDocumentModels(selectedFileName);

            AnalyzerBase analyzer      = null;
            var          codeBehindExt = string.Empty;

            switch (fileExt)
            {
            case ".cs":
                analyzer      = new CSharpAnalyzer(this.logger);
                codeBehindExt = ((CSharpAnalyzer)analyzer).FileExtension;
                break;

            case ".vb":
                analyzer      = new VisualBasicAnalyzer(this.logger);
                codeBehindExt = ((VisualBasicAnalyzer)analyzer).FileExtension;
                break;
            }

            this.CreateView = false;

            if (analyzer != null)
            {
                // IndexOf is allowing for "class " in C# and "Class " in VB
                var analyzerOutput = ((IDocumentAnalyzer)analyzer).GetSingleItemOutput(syntaxTree.GetRoot(), semModel, fileContents.IndexOf("lass "), this.profile);

                var config = this.profile.ViewGeneration;

                var vmClassName = analyzerOutput.Name;

                var baseClassName = vmClassName;

                if (vmClassName.EndsWith(config.ViewModelFileSuffix))
                {
                    baseClassName = vmClassName.Substring(0, vmClassName.LastIndexOf(config.ViewModelFileSuffix, StringComparison.InvariantCulture));
                }

                var viewClassName = $"{baseClassName}{config.XamlFileSuffix}";

                var    vmProjName = vmProj.Name;
                string viewProjName;

                this.ViewProject = null;

                if (config.AllInSameProject)
                {
                    this.ViewProject = vmProj;
                    viewProjName     = this.ViewProject.Name;
                }
                else
                {
                    var expectedViewProjectName = vmProjName.Replace(config.ViewModelProjectSuffix, config.XamlProjectSuffix);

                    this.ViewProject = this.vs.GetProject(expectedViewProjectName);

                    if (this.ViewProject == null)
                    {
                        this.logger.RecordError($"Unable to find project '{expectedViewProjectName}' in the solution.");
                    }

                    viewProjName = this.ViewProject?.Name;
                }

                if (this.ViewProject != null)
                {
                    var folder = this.fileSystem.GetDirectoryName(this.ViewProject.FileName);

                    this.ViewFolder = this.fileSystem.PathCombine(folder, config.XamlFileDirectoryName);

                    // We assume that the type name matches the file name.
                    this.XamlFileName = this.fileSystem.PathCombine(this.ViewFolder, $"{viewClassName}.xaml");
                    this.CodeFileName = this.fileSystem.PathCombine(this.ViewFolder, $"{viewClassName}.xaml.{codeBehindExt}");

                    if (this.fileSystem.FileExists(this.XamlFileName))
                    {
                        this.logger.RecordInfo($"File '{this.XamlFileName}' already exists");

                        var overwrite = this.vs.UserConfirms("File already exists", "Do you want to override the existing file?");

                        if (overwrite)
                        {
                            this.CreateView = true;
                            this.logger.RecordInfo($"Overwriting '{this.XamlFileName}'");
                        }
                        else
                        {
                            this.logger.RecordInfo($"Not overwriting '{this.XamlFileName}'");
                        }
                    }
                    else
                    {
                        this.CreateView = true;
                    }

                    if (this.CreateView)
                    {
                        var viewNamespace = analyzer is CSharpAnalyzer
                                          ? $"{viewProjName}.{config.XamlFileDirectoryName}".TrimEnd('.')
                                          : $"{config.XamlFileDirectoryName}".TrimEnd('.');

                        var vmNamespace = $"{vmProjName}.{config.ViewModelDirectoryName}".TrimEnd('.');

                        var replacementValues = (viewProjName, viewNamespace, vmNamespace, viewClassName, vmClassName, analyzerOutput.Output);

                        this.XamlFileContents = this.ReplacePlaceholders(config.XamlPlaceholder, replacementValues);
                        this.CodeFileContents = this.ReplacePlaceholders(config.CodePlaceholder, replacementValues);
                    }
                }
            }
        }