Пример #1
0
        /// <summary>
        /// Adds the item template to project.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="templateInfos">The template infos.</param>
        public static void AddItemTemplateToProjects(
            this Solution2 instance,
            IEnumerable <ItemTemplateInfo> templateInfos)
        {
            IEnumerable <Project> projects = instance.GetProjects();

            TraceService.WriteError("AddItemTemplateToProjects project count=" + projects.Count());

            foreach (ItemTemplateInfo info in templateInfos)
            {
                Project project = projects.FirstOrDefault(x => x.Name.EndsWith(info.ProjectSuffix));

                if (project != null)
                {
                    project.AddToFolderFromTemplate(info.FolderName, info.TemplateName, info.FileName);
                }

                else
                {
                    TraceService.WriteError("AddItemTemplateToProjects cannot find project " + info.ProjectSuffix);

                    foreach (Project projectItem in projects)
                    {
                        string projectName = projectItem.Name;

                        TraceService.WriteError("AddItemTemplateToProjects project " + projectName);
                    }
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Replaces the text.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="findText">The find text.</param>
        /// <param name="replaceText">The replace text.</param>
        /// <param name="saveFiles">if set to <c>true</c> [save files].</param>
        /// <returns>True or false.</returns>
        public static bool ReplaceText(
            this DTE2 instance,
            string findText,
            string replaceText,
            bool saveFiles)
        {
            TraceService.WriteLine("DTEExtensions::ReplaceText from '" + findText + "' to '" + replaceText + "'");

            bool replaced = true;

            Find2 find2 = (Find2)instance.Find;

            vsFindResult findResults = find2.FindReplace(
                vsFindAction.vsFindActionReplaceAll,
                findText,
                (int)vsFindOptions.vsFindOptionsFromStart,
                replaceText,
                vsFindTarget.vsFindTargetSolution,
                string.Empty,
                string.Empty,
                vsFindResultsLocation.vsFindResultsNone);

            if (findResults == vsFindResult.vsFindResultNotFound)
            {
                replaced = false;
                TraceService.WriteError("Unable to replace text from:-" + findText + " to:- " + replaceText);
            }

            if (saveFiles)
            {
                instance.SaveAll();
            }

            return(replaced);
        }
        /// <summary>
        /// Translates the specified from.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns></returns>
        public CustomRenderers Translate(string from)
        {
            TraceService.WriteLine("CustomRenderers::Translate " + from);

            CustomRenderers customRenderers = new CustomRenderers();

            try
            {
                XDocument doc = XDocument.Load(@from);

                if (doc.Root != null)
                {
                    TraceService.WriteDebugLine(doc.Root.Value);

                    customRenderers.HelpLink = this.GetHelpLink(doc.Root);
                    customRenderers.Groups   = this.GetGroups(doc.Root);
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError(exception);
            }

            return(customRenderers);
        }
        /// <summary>
        /// Gets the first class.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns>The first class.</returns>
        public static CodeClass GetFirstClass(this ProjectItem instance)
        {
            TraceService.WriteLine("ProjectItemExtensions::GetFirstClass file=" + instance.Name);

            IEnumerable <CodeClass> codeClasses = instance.FileCodeModel.CodeElements.OfType <CodeClass>();

            if (!codeClasses.Any())
            {
                CodeNamespace codeNamespace = instance.GetFirstNameSpace();

                if (codeNamespace != null)
                {
                    foreach (CodeElement codeElement in codeNamespace.Children)
                    {
                        if (codeElement.Kind == vsCMElement.vsCMElementClass)
                        {
                            return(codeElement as CodeClass);
                        }
                    }
                }
                else
                {
                    TraceService.WriteError("ProjectItemExtensions::GetFirstClass cannot find namespace");
                }
            }
            else
            {
                return(codeClasses.FirstOrDefault());
            }

            return(null);
        }
Пример #5
0
        /// <summary>
        /// Gets the plugins.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>The plugins.</returns>
        public Plugins GetPlugins(string uri)
        {
            TraceService.WriteLine("PluginFactory::GetPlugins url=" + uri);

            if (this.cachingService.Plugins.ContainsKey(uri))
            {
                TraceService.WriteLine("Using cache");
                return(this.cachingService.Plugins[uri]);
            }

            Plugins plugins = this.pluginsTranslator.Translate(uri);

            if (plugins != null)
            {
                if (plugins.Items != null)
                {
                    TraceService.WriteLine("PluginFactory::GetPlugins pluginCount=" + plugins.Items.Count());
                    this.cachingService.Plugins.Add(uri, plugins);
                }
                else
                {
                    TraceService.WriteLine("PluginFactory::GetPlugins has no plugins");
                }
            }
            else
            {
                TraceService.WriteError("PluginFactory::GetPlugins is null url=" + uri);
            }

            return(plugins);
        }
        /// <summary>
        /// Processes the specified form.
        /// </summary>
        /// <param name="effectViewModel">The effect view model.</param>
        internal void Process(EffectViewModel effectViewModel)
        {
            TraceService.WriteLine("EffectsController::Process");

            this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.NinjaIsRunning);

            try
            {
                TraceService.WriteLine("EffectsController::Process GetTextTemplates");

                IEnumerable <TextTemplateInfo> textTemplates = this.effectFactory.GetTextTemplates(
                    effectViewModel.RequestedName,
                    this.SettingsService.EffectDirectory);

                IEnumerable <string> messages = this.textTemplatingService.AddTextTemplates(
                    NinjaMessages.AddingEffect,
                    textTemplates);

                //// show the readme.
                this.ShowReadMe("Add Xamarin Forms Effect", messages);
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Cannot create effect exception=" + exception.Message);
            }
        }
Пример #7
0
        /// <summary>
        /// Deletes the command.
        /// </summary>
        /// <param name="commandName">Name of the command.</param>
        protected void DeleteCommand(string commandName)
        {
            TraceService.WriteLine("CommandManager::DeleteCommand commandName=" + commandName);

            try
            {
                Commands2       commands       = (Commands2)this.VsInstance.ApplicationObject.Commands;
                CommandBarPopup toolsMenuPopUp = this.VsInstance.ApplicationObject.GetToolsMenuPopUp();

                CommandBar commandBar = null;

                for (int i = 1; i <= toolsMenuPopUp.CommandBar.Controls.Count; i++)
                {
                    if (toolsMenuPopUp.CommandBar.Controls[i].Caption == commandName)
                    {
                        TraceService.WriteLine("CommandManager::DeleteCommand commandFound in collection commandName=" + commandName);
                        CommandBarPopup commandBarPopup = (CommandBarPopup)toolsMenuPopUp.CommandBar.Controls[i];

                        commandBar = commandBarPopup.CommandBar;
                        break;
                    }
                }

                if (commandBar != null)
                {
                    TraceService.WriteLine("Command found and will be deleted ommandName=" + commandName);
                    commandBar.Delete();
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("exception=" + exception.Message);
                TraceService.WriteError("stackTrace=" + exception.StackTrace);
            }
        }
Пример #8
0
        /// <summary>
        /// Processes the specified form.
        /// </summary>
        /// <param name="customRendererViewModel">The custom renderer view model.</param>
        internal void Process(CustomRendererViewModel customRendererViewModel)
        {
            TraceService.WriteLine("CustomerRendererController::Process");

            this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.NinjaIsRunning);

            try
            {
                TraceService.WriteLine("CustomerRendererController::Process GetTextTemplates");

                IEnumerable <TextTemplateInfo> textTemplates = this.customRendererFactory.GetTextTemplates(
                    customRendererViewModel.RequestedName,
                    this.SettingsService.CustomRendererDirectory,
                    customRendererViewModel.SelectedCustomRendererItem,
                    customRendererViewModel.CodeBlock);

                IEnumerable <string> messages = this.textTemplatingService.AddTextTemplates(
                    NinjaMessages.AddingCustomRenderer,
                    textTemplates);

                //// show the readme.
                this.ShowReadMe("Add Xamarin Forms Custom Renderer", messages);
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Cannot create custom renderer exception=" + exception.Message);
            }
        }
Пример #9
0
        /// <summary>
        /// Builds the source file.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="extensionSource">The extensionSource.</param>
        /// <param name="extensionDestination">The extension destination.</param>
        /// <param name="friendlyName">Name of the friendly.</param>
        internal void BuildSourceFile(
            Project project,
            string extensionSource,
            string extensionDestination,
            string friendlyName)
        {
            try
            {
                const string PlaceHolderText = "#PlaceHolder#";

                string message = string.Format("BuildSourceFile Project Name={0} friendlyName={1}", project.Name, friendlyName);

                TraceService.WriteLine(message);

                string sourceFile = friendlyName + "PluginBootstrap.cs";

                //// now we need to sort out the item template!
                project.AddToFolderFromTemplate("Bootstrap", "MvvmCross.Plugin.zip", sourceFile);

                ProjectItem projectItem = project.GetProjectItem(sourceFile);

                //// if we find the project item replace the text in it else use the find/replace window.
                if (projectItem != null)
                {
                    TextSelection textSelection = projectItem.DTE.ActiveDocument.Selection;
                    textSelection.SelectAll();
                    textSelection.ReplacePattern(PlaceHolderText, friendlyName);
                    projectItem.Save();
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("BuildSourceFile " + exception.Message);
            }
        }
Пример #10
0
        /// <summary>
        /// Sets the start up project.
        /// </summary>
        public void SetStartUpProject()
        {
            if (this.IsNewSolution)
            {
                return;
            }

            string startUpProject = this.SettingsService.StartUpProject;

            TraceService.WriteLine("StartUpProject=" + startUpProject);

            if (startUpProject != string.Empty)
            {
                IProjectService projectService = this.visualStudioService.GetProjectServiceBySuffix(startUpProject);

                if (projectService != null)
                {
                    this.visualStudioService.SolutionService.SetStartUpProject(projectService.Name);
                }
                else
                {
                    TraceService.WriteError("Cannot find StartUpProject=" + startUpProject);
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Processes the specified form.
        /// </summary>
        /// <param name="dependencyServiceViewModel">The dependency service view model.</param>
        internal void Process(DependencyServiceViewModel dependencyServiceViewModel)
        {
            TraceService.WriteLine("DependencyServicesController::Process");

            this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.NinjaIsRunning);

            try
            {
                TraceService.WriteLine("DependencyServicesController::Process GetTextTemplates");

                IEnumerable <TextTemplateInfo> textTemplates = this.dependencyServicesFactory.GetTextTemplates(
                    dependencyServiceViewModel.RequestedName,
                    dependencyServiceViewModel.MethodComment,
                    dependencyServiceViewModel.MethodReturnType,
                    dependencyServiceViewModel.MethodName,
                    this.SettingsService.DependencyDirectory);

                IEnumerable <string> messages = this.textTemplatingService.AddTextTemplates(
                    NinjaMessages.AddingDependencyService,
                    textTemplates);

                //// show the readme.
                this.ShowReadMe("Add Xamarin Forms Dependency Service", messages);
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Cannot create dependency service exception=" + exception.Message);
            }
        }
Пример #12
0
        /// <summary>
        /// Completed the nuget updates.
        /// </summary>
        internal void NugetCompleted()
        {
            TraceService.WriteLine("NugetService::NugetCompleted");

            if (this.documentEvents != null)
            {
                this.RemoveEventHandlers();
            }

            this.ExecutePostNugetCommands();
            this.ExecutePostNugetFileOperations();

            this.visualStudioService.DTEService.CollapseSolution();

            if (this.ResumeReSharper)
            {
                try
                {
                    //// this could fail - so catch exception.
                    this.visualStudioService.DTEService.ExecuteCommand(Settings.ResumeReSharperCommand);
                }
                catch (Exception exception)
                {
                    TraceService.WriteError("Error Resuming ReSharper exception=" + exception.Message);
                }
            }
        }
        /// <summary>
        /// Shows the read me.
        /// </summary>
        /// <param name="function">The function.</param>
        /// <param name="messages">The messages.</param>
        /// <param name="closeDocuments">if set to <c>true</c> [close documents].</param>
        /// <param name="collapseSolution">if set to <c>true</c> [collapse solution].</param>
        protected void ShowReadMe(
            string function,
            IEnumerable <string> messages,
            bool closeDocuments   = true,
            bool collapseSolution = true)
        {
            TraceService.WriteLine("BaseController::ShowReadMe " + function);

            //// never quite got to the bottom this but sometimes closing documents/collapsing the solution fails.
            //// this isnt that important - but we need to show the readme file - so catch the error.

            try
            {
                //// close any open documents.
                if (closeDocuments)
                {
                    this.VisualStudioService.DTEService.CloseDocuments();
                }

                //// now collapse the solution!
                if (collapseSolution)
                {
                    this.VisualStudioService.DTEService.CollapseSolution();
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Error closing documents/solution exception=" + exception.Message);
            }

            try
            {
                string readMePath = this.GetReadMePath();

                TraceService.WriteLine("BaseController::ShowReadMe path=" + readMePath);

                //// now construct the ReadMe.txt
                this.ReadMeLines.AddRange(messages);

                this.ReadMeService.AddLines(
                    readMePath,
                    function,
                    this.ReadMeLines,
                    TraceService.ErrorMessages,
                    this.GetTraceMessages(false));

                this.VisualStudioService.DTEService.OpenFile(readMePath);

                //// reset the messages - if we don't do this we get the previous messages!
                this.readmeLines = new List <string>();
            }
            catch (Exception exception)
            {
                TraceService.WriteError("BaseController::ShowReadMe Showing ReadMe Error :-" + exception.Message);
            }
        }
        /// <summary>
        /// Processes the specified form.
        /// </summary>
        /// <param name="plugins">The plugins.</param>
        internal void Process(IEnumerable <Plugin> plugins)
        {
            TraceService.WriteLine("PluginsController::Process");

            this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.NinjaIsRunning);

            try
            {
                List <string> messages = new List <string>();

                this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.UpdatingFiles);

                this.VisualStudioService.DTEService.SaveAll();

                List <string> commands = plugins.Select(plugin => plugin.GetNugetCommandStrings(
                                                            this.VisualStudioService,
                                                            this.SettingsService,
                                                            this.SettingsService.UsePreReleaseMvvmCrossNugetPackages)).ToList();

                if (commands.Any())
                {
                    if (this.SettingsService.ProcessNugetCommands)
                    {
                        this.nugetService.Execute(
                            this.GetReadMePath(),
                            commands,
                            this.SettingsService.SuspendReSharperDuringBuild);
                    }

                    string message = NinjaMessages.NugetDownload;

                    if (this.SettingsService.UseLocalNuget)
                    {
                        message += " (using local " + this.SettingsService.LocalNugetName + ")";
                    }

                    this.VisualStudioService.WriteStatusBarMessage(message);
                }

                if (this.SettingsService.OutputNugetCommandsToReadMe)
                {
                    messages.Add(string.Join(Environment.NewLine, commands));
                }

                this.ReadMeService.AddLines(
                    this.GetReadMePath(),
                    "Add MvvmCross Plugins",
                    messages,
                    TraceService.ErrorMessages,
                    this.GetTraceMessages(false));
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Cannot create plugins exception=" + exception.Message);
            }
        }
        /// <summary>
        /// Adds the item template to project.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="templateInfos">The template infos.</param>
        /// <returns>
        /// The messages.
        /// </returns>
        public static IEnumerable <string> AddItemTemplateToProjects(
            this Solution2 instance,
            IEnumerable <ItemTemplateInfo> templateInfos)
        {
            string method = "SolutionExtensions::AddItemTemplateToProjects ";

            TraceService.WriteLine(method);

            List <string> messages = new List <string>();

            IEnumerable <Project> projects = instance.GetProjects();

            IEnumerable <Project> projectItems = projects as Project[] ?? projects.ToArray();

            foreach (ItemTemplateInfo info in templateInfos)
            {
                Project project = projectItems.FirstOrDefault(x => x.Name.EndsWith(info.ProjectSuffix));

                if (project != null)
                {
                    string context = project.Name + "  (template=" + info.TemplateName + ") fileName=" + info.FileName;

                    TraceService.WriteLine(method + context);

                    try
                    {
                        if (project.AddItemToFolderFromTemplate(info.TemplateName, info.FileName))
                        {
                            messages.Add(info.FileName + " added to " + project.Name + " project (template=" + info.TemplateName + ")");
                        }
                    }
                    catch (Exception exception)
                    {
                        TraceService.WriteError(method + context + " exception=" + exception.Message);
                        messages.Add(method + context + " exception=" + exception.Message);
                    }
                }
                else
                {
                    TraceService.WriteError(method + " cannot find project " + info.ProjectSuffix);

                    foreach (string projectName in projectItems
                             .Select(projectItem => projectItem.Name))
                    {
                        TraceService.WriteError(method + " project " + projectName);
                        messages.Add(info.FileName + " added to " + projectName + " project (template=" + info.TemplateName + ")");
                    }
                }
            }

            return(messages);
        }
        /// <summary>
        /// Runs this instance.
        /// </summary>
        public void Run()
        {
            TraceService.WriteHeader("ProjectsController::Run");

            //// we open the nuget package manager console so we don't have a wait condition later!

            this.nugetService.OpenNugetWindow();

            this.projectFactory.RegisterWizardData();

            WizardFrameViewModel viewModel = this.ShowDialog <WizardFrameViewModel>(new WizardView());

            try
            {
                if (viewModel.Continue)
                {
                    ProjectsViewModel                  projectsViewModel                  = (ProjectsViewModel)viewModel.GetWizardStepViewModel("ProjectsViewModel").ViewModel;
                    ApplicationOptionsViewModel        applicationOptionsViewModel        = (ApplicationOptionsViewModel)viewModel.GetWizardStepViewModel("ApplicationOptionsViewModel").ViewModel;
                    NinjaCoderOptionsViewModel         ninjaCoderOptionsViewModel         = (NinjaCoderOptionsViewModel)viewModel.GetWizardStepViewModel("NinjaCoderOptionsViewModel").ViewModel;
                    ApplicationSamplesOptionsViewModel applicationSamplesOptionsViewModel = (ApplicationSamplesOptionsViewModel)viewModel.GetWizardStepViewModel("ApplicationSamplesOptionsViewModel").ViewModel;
                    ViewsViewModel            viewsViewModel            = (ViewsViewModel)viewModel.GetWizardStepViewModel("ViewsViewModel").ViewModel;
                    PluginsViewModel          pluginsViewModel          = (PluginsViewModel)viewModel.GetWizardStepViewModel("PluginsViewModel").ViewModel;
                    NugetPackagesViewModel    nugetPackagesViewModel    = (NugetPackagesViewModel)viewModel.GetWizardStepViewModel("NugetPackagesViewModel").ViewModel;
                    XamarinFormsLabsViewModel xamarinFormsLabsViewModel = (XamarinFormsLabsViewModel)viewModel.GetWizardStepViewModel("XamarinFormsLabsViewModel").ViewModel;

                    this.Process(
                        projectsViewModel,
                        applicationOptionsViewModel,
                        ninjaCoderOptionsViewModel,
                        applicationSamplesOptionsViewModel,
                        viewsViewModel,
                        pluginsViewModel,
                        nugetPackagesViewModel,
                        xamarinFormsLabsViewModel);
                }
            }
            catch (Exception exception)
            {
                //// TODO : this needs refactoring.

                this.VisualStudioService.WriteStatusBarMessage(string.Empty);
                TraceService.WriteError(exception);

                //// put the error messages in the readme!
                this.messages.InsertRange(0, TraceService.ErrorMessages);

                TraceService.ErrorMessages = new List <string>();

                this.CreateReadMe(true, true);
            }
        }
Пример #17
0
        /// <summary>
        /// Implements the interface.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="constructor">The constructor.</param>
        /// <param name="variable">The variable.</param>
        public static void ImplementInterface(
            this CodeClass instance,
            CodeFunction constructor,
            string variable)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementInterface file=" + variable);

            //// now add in the interfaces!

            //// split the variable string
            string[] parts = variable.Split(' ');

            constructor.AddParameter(parts[1], parts[0]);

            //// we need to add the variable.
            //// variable could already exist!
            try
            {
                instance.ImplementVariable(parts[1], parts[0], true);
            }
            catch (Exception)
            {
                TraceService.WriteError("variable already exists " + parts[1]);
            }

            //// now do the wiring up of the interface and variable!
            EditPoint editPoint = constructor.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            string code = string.Format("this.{0} = {1};", parts[1], parts[1]);

            editPoint.InsertCodeLine(code);

            //// now update the constructor document comments.
            string paramComment   = string.Format("<param name=\"{0}\">The {0}.</param>{1}", parts[1], Environment.NewLine);
            string currentComment = constructor.DocComment;

            int index = currentComment.LastIndexOf("</summary>", StringComparison.Ordinal);

            StringBuilder sb = new StringBuilder();

            if (index != -1)
            {
                sb.Append(currentComment.Substring(0, index + 10));
                sb.Append(paramComment);
                sb.Append(currentComment.Substring(index + 10));

                TraceService.WriteLine("comment added=" + paramComment);
            }

            constructor.DocComment = sb.ToString();
        }
        /// <summary>
        /// Adds to folder from template.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="folderName">Name of the folder.</param>
        /// <param name="templateName">Name of the template.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="createFolder">if set to <c>true</c> [create folder].</param>
        /// <returns>True or False.</returns>
        public static bool AddToFolderFromTemplate(
            this Project instance,
            string folderName,
            string templateName,
            string fileName,
            bool createFolder)
        {
            TraceService.WriteLine("ProjectExtensions::AddToFolderFromTemplate project=" + instance.Name);

            string       path         = instance.Properties.Item("FullPath").Value;
            ProjectItems projectItems = instance.ProjectItems;

            //// this supports passing of folder name - currently used by viewmodels and views.
            //// may not be required if we refactor the item templates to embed the directory.
            if (createFolder)
            {
                ProjectItem folderProjectItem = instance.ProjectItems
                                                .Cast <ProjectItem>()
                                                .FirstOrDefault(projectItem => projectItem.Name == folderName);

                //// if the folder doesn't exist create it.
                if (folderProjectItem == null)
                {
                    folderProjectItem = instance.ProjectItems.AddFolder(folderName);
                }

                projectItems = folderProjectItem.ProjectItems;

                path = folderProjectItem.Properties.Item("FullPath").Value;
            }

            Solution2 solution = instance.DTE.Solution as Solution2;

            string templatePath = solution.GetProjectItemTemplate(templateName);

            if (templatePath != null)
            {
                string filePath = string.Format(@"{0}\{1}\{2}", path, folderName, fileName);

                if (File.Exists(filePath) == false)
                {
                    projectItems.AddFromTemplate(templatePath, fileName);
                }

                return(true);
            }

            TraceService.WriteError("ProjectExtensions::AddToFolderFromTemplate Cannot find template " + templateName);

            return(false);
        }
Пример #19
0
        /// <summary>
        /// Add item to the menu.
        /// </summary>
        /// <param name="vsCommandInfo">The command info.</param>
        protected virtual void AddMenuItem(VSCommandInfo vsCommandInfo)
        {
            TraceService.WriteLine("CommandManager::AddMenuItem Name=" + vsCommandInfo.Name);

            //// This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
            //// just make sure you also update the QueryStatus/Exec method to include the new command names.
            try
            {
                Commands2 commands = (Commands2)this.VSInstance.ApplicationObject.Commands;
                object[]  context  = new object[] { };

                TraceService.WriteLine("CommandManager::AddMenuItem Adding command name=" + vsCommandInfo.Name);

                IEnumerable <Command> currentCommands = commands.Cast <Command>();

                foreach (Command command in currentCommands
                         .Where(command => command.Name == vsCommandInfo.Name))
                {
                    TraceService.WriteLine("CommandManager::AddMenuItem Deleting Command already in memory name=" + vsCommandInfo.Name);
                    command.Delete();
                    break;
                }

                vsCommandInfo.Command = commands.AddNamedCommand2(
                    vsCommandInfo.AddIn,
                    vsCommandInfo.Name,
                    vsCommandInfo.ButtonText,
                    vsCommandInfo.Tooltip,
                    vsCommandInfo.UseOfficeResources,
                    vsCommandInfo.BitmapResourceId,
                    ref context);

                vsCommandInfo.Command.AddControl(vsCommandInfo.ParentCommand, vsCommandInfo.Position);

                this.commandInfos.Add(vsCommandInfo);
            }
            catch (ArgumentException exception)
            {
                //// If we are here, then the exception is probably because a command with that name
                //// already exists. If so there is no need to recreate the command and we can
                //// safely ignore the exception.

                TraceService.WriteError("CommandManager::AddMenuItem ArgumentException");
                TraceService.WriteLine("commandName=" + vsCommandInfo.Name);
                TraceService.WriteError("message=" + exception.Message);
                TraceService.WriteError("parameterName=" + exception.ParamName);
                TraceService.WriteError("stackTrace=" + exception.StackTrace);
            }
        }
        /// <summary>
        /// Gets the project path.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns>The project path.</returns>
        public static string GetProjectPath(this Project instance)
        {
            string path = string.Empty;

            try
            {
                path = Path.GetDirectoryName(instance.FullName);
            }
            catch (Exception exception)
            {
                TraceService.WriteError("ProjectExtensions::GetProjectPath exception=" + exception.Message);
            }

            return(path);
        }
Пример #21
0
        /// <summary>
        /// Sorts the and remove using statements.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void SortAndRemoveUsingStatements(this ProjectItem instance)
        {
            try
            {
                string ConstantsvsViewKindCode = "{7651A701-06E5-11D1-8EBD-00A0C90F26EA}";
                Window window = instance.Open(ConstantsvsViewKindCode);

                window.Activate();

                instance.DTE.ExecuteCommand("Edit.RemoveAndSort");
            }
            catch (Exception exception)
            {
                TraceService.WriteError("SortAndRemoveUsingStatements " + exception.Message);
            }
        }
Пример #22
0
        /// <summary>
        /// Moves the using statements.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void MoveUsingStatements(this ProjectItem instance)
        {
            List <string> usingStatements = new List <string>();

            try
            {
                foreach (CodeElement codeElement in instance.FileCodeModel.CodeElements)
                {
                    //// assume the using statements come before the required namespace.
                    if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                    {
                        TextPoint startPoint = codeElement.StartPoint;
                        TextPoint endPoint   = codeElement.EndPoint;

                        string text = startPoint.CreateEditPoint().GetText(endPoint);
                        usingStatements.Add(text);
                    }
                    else if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
                    {
                        TextPoint nameSpacePoint = codeElement.GetStartPoint(vsCMPart.vsCMPartBody);
                        EditPoint editPoint      = nameSpacePoint.CreateEditPoint();

                        foreach (string statement in usingStatements)
                        {
                            editPoint.Insert("\t" + statement + "\n");
                        }
                    }
                }

                //// now perform the deletes.
                for (int i = 1; i <= instance.FileCodeModel.CodeElements.Count; i++)
                {
                    CodeElement codeElement = instance.FileCodeModel.CodeElements.Item(i);

                    if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                    {
                        instance.FileCodeModel.Remove(codeElement);
                    }
                }
            }

            catch (Exception exception)
            {
                TraceService.WriteError("MoveUsingStatements " + exception.Message);
            }
        }
Пример #23
0
        /// <summary>
        /// Suspends the resharper if requested.
        /// </summary>
        public void SuspendResharperIfRequested()
        {
            if (this.settingsService.SuspendReSharperDuringBuild)
            {
                TraceService.WriteLine("SuspendResharper");

                try
                {
                    //// this could fail so catch exception.
                    this.visualStudioService.DTEService.ExecuteCommand(Settings.SuspendReSharperCommand);
                }
                catch (Exception exception)
                {
                    TraceService.WriteError("Error Suspending ReSharper exception=" + exception.Message);
                }
            }
        }
        /// <summary>
        /// Sorts the and remove using statements.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void SortAndRemoveUsingStatements(this ProjectItem instance)
        {
            TraceService.WriteLine("ProjectItemExtensions::SortAndRemoveUsingStatements in file " + instance.Name);

            try
            {
                Window window = instance.Open(VSConstants.VsViewKindCode);

                window.Activate();

                instance.DTE.ExecuteCommand("Edit.RemoveAndSort");
            }
            catch (Exception exception)
            {
                TraceService.WriteError("SortAndRemoveUsingStatements " + exception.Message);
            }
        }
        /// <summary>
        /// Adds the converters.
        /// </summary>
        public void AddConverters()
        {
            this.AddTraceHeader("AddConverters");

            if (this.visualStudioService.IsMvvmCrossSolution)
            {
                string templatesPath = this.settingsService.ConvertersTemplatesPath;

                List <ItemTemplateInfo> itemTemplateInfos = this.visualStudioService.GetFolderTemplateInfos(templatesPath, "Converters");

                ItemTemplatesForm form = new ItemTemplatesForm(itemTemplateInfos);

                form.ShowDialog();

                if (form.Continue)
                {
                    this.visualStudioService.DTE2.WriteStatusBarMessage("Ninja Coder is running....");

                    Project project = this.visualStudioService.CoreProject;

                    if (project != null)
                    {
                        foreach (ItemTemplateInfo templateInfo in form.RequiredTemplates)
                        {
                            TraceService.WriteLine("MvvmCrossController::AddConverters adding from template path " + templatesPath + " template=" + templateInfo.FileName);

                            project.AddToFolderFromTemplate("Converters", templateInfo.FileName, templateInfo.FriendlyName + ".cs");
                        }

                        //// now collapse the solution!
                        this.visualStudioService.DTE2.CollapseSolution();

                        this.visualStudioService.DTE2.WriteStatusBarMessage("Ninja Coder has completed the adding of the converters.");
                    }
                    else
                    {
                        TraceService.WriteError("MvvmCrossController::AddConverters Cannot find Core project");
                    }
                }
            }
            else
            {
                MessageBox.Show("This solution is not a MvvmCross solution.", Settings.ApplicationName);
            }
        }
        /// <summary>
        /// Replaces the text.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="text">The text.</param>
        /// <param name="replacementText">The replacement text.</param>
        /// <param name="findOptions">The find options.</param>
        public static void ReplaceText(
            this ProjectItem instance,
            string text,
            string replacementText,
            int findOptions = (int)vsFindOptions.vsFindOptionsMatchCase)
        {
            TraceService.WriteLine("ProjectItemExtensions::ReplaceText in file " + instance.Name + " from '" + text + "' to '" + replacementText + "'");

            if (instance.Kind == VSConstants.VsProjectItemKindPhysicalFolder)
            {
                foreach (ProjectItem projectItem in instance.ProjectItems.Cast <ProjectItem>())
                {
                    projectItem.ReplaceText(text, replacementText);
                }

                return;
            }

            try
            {
                Window window = instance.Open(VSConstants.VsViewKindCode);

                if (window != null)
                {
                    window.Activate();

                    TextSelection textSelection = instance.DTE.ActiveDocument.Selection;
                    textSelection.SelectAll();

                    bool replaced = textSelection.ReplacePattern(text, replacementText, findOptions);

                    TraceService.WriteLine(replaced ? "Replaced" : "NOT replaced");

                    instance.Save();
                }
                else
                {
                    TraceService.WriteLine("Could not open window to do replacement for " + instance.Name);
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Replacing Text failed for " + instance.Name + " exception=" + exception);
            }
        }
        /// <summary>
        /// Moves the using statements.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void MoveUsingStatements(this ProjectItem instance)
        {
            TraceService.WriteLine("ProjectItemExtensions::MoveUsingStatements in file " + instance.Name);

            List <string> usingStatements = new List <string>();

            try
            {
                foreach (CodeElement codeElement in instance.FileCodeModel.CodeElements)
                {
                    //// assume the using statements come before the required namespace.
                    switch (codeElement.Kind)
                    {
                    case vsCMElement.vsCMElementImportStmt:

                        TextPoint startPoint = codeElement.StartPoint;
                        TextPoint endPoint   = codeElement.EndPoint;

                        string text = startPoint.CreateEditPoint().GetText(endPoint);
                        usingStatements.Add(text);

                        break;

                    case vsCMElement.vsCMElementNamespace:

                        TextPoint nameSpacePoint = codeElement.GetStartPoint(vsCMPart.vsCMPartBody);
                        EditPoint editPoint      = nameSpacePoint.CreateEditPoint();

                        foreach (string statement in usingStatements)
                        {
                            editPoint.Insert("\t" + statement + "\n");
                        }

                        break;
                    }
                }

                instance.DeleteNameSpaceUsingStatements();
            }
            catch (Exception exception)
            {
                TraceService.WriteError("MoveUsingStatements " + exception.Message);
            }
        }
Пример #28
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        public void Run()
        {
            this.AddTraceHeader("ServicesController", "Run");

            if (this.VisualStudioService.IsMvvmCrossSolution)
            {
                string templatesPath = this.SettingsService.ServicesTemplatesPath;

                List <ItemTemplateInfo> itemTemplateInfos = this.VisualStudioService.GetFolderTemplateInfos(templatesPath, "Services");

                ServicesForm form = new ServicesForm(this.GetViewModelNames(), itemTemplateInfos, this.SettingsService.DisplayLogo);

                form.ShowDialog();

                if (form.Continue)
                {
                    this.WriteStatusBarMessage("Ninja Coder is running....");

                    Project project = this.VisualStudioService.CoreProject;

                    if (project != null)
                    {
                        List <string> messages = this.servicesService.AddServices(
                            this.VisualStudioService,
                            form.RequiredTemplates,
                            form.ImplementInViewModel,
                            form.IncludeUnitTests);

                        //// show the readme.
                        this.ShowReadMe("Add Services", messages);

                        this.WriteStatusBarMessage("Ninja Coder has completed the adding of the services.");
                    }
                    else
                    {
                        TraceService.WriteError("ServicesController::AddServices Cannot find Core project");
                    }
                }
            }
            else
            {
                this.ShowNotMvvmCrossSolutionMessage();
            }
        }
Пример #29
0
        /// <summary>
        /// Lists all commands.
        /// </summary>
        protected void ListAllCommands()
        {
            TraceService.WriteLine("CommandManager::ListAllCommands");

            try
            {
                Commands2       commands       = (Commands2)this.VsInstance.ApplicationObject.Commands;
                CommandBarPopup toolsMenuPopUp = this.VsInstance.ApplicationObject.GetToolsMenuPopUp();

                for (int i = 1; i <= toolsMenuPopUp.CommandBar.Controls.Count; i++)
                {
                    TraceService.WriteLine(toolsMenuPopUp.CommandBar.Controls[i].Caption);
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("exception=" + exception.Message);
            }
        }
        /// <summary>
        /// Gets the folder.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="folderName">Name of the folder.</param>
        /// <returns>The folder.</returns>
        public static ProjectItem GetFolder(
            this Project instance,
            string folderName)
        {
            TraceService.WriteDebugLine("ProjectExtensions::GetFolder project=" + instance.Name + " folderName=" + folderName);

            try
            {
                List <ProjectItem> projectItems = instance.ProjectItems?.Cast <ProjectItem>().ToList();

                return(projectItems?.Where(projectItem => projectItem.Kind == VSConstants.VsProjectItemKindPhysicalFolder)
                       .FirstOrDefault(projectItem => projectItem.Name == folderName));
            }
            catch (Exception exception)
            {
                TraceService.WriteError("exception=" + exception.Message);
                return(null);
            }
        }