Пример #1
0
        public void GetVisualStudioSolutionFilesInnerTests()
        {
            {
                // 1
                var tmpFolder = GetTempFolder();
                var project1  = this.CreateProject(tmpFolder, "Project1");
                var project2  = this.CreateProject(tmpFolder, "Project2");
                var project3  = this.CreateProject(tmpFolder, "Project3");

                var actual = VisualStudioHelper.GetVisualStudioSolutionFiles(tmpFolder, tmpFolder).ToArray();
                this.Assert(actual, new[]
                {
                    project1, project2, project3
                });
            }
            {
                // 2
                var tmpFolder = GetTempFolder();
                var project1  = this.CreateProject(tmpFolder, "Project1");
                var project2  = this.CreateProject(tmpFolder, "Project2");
                var project3  = this.CreateProject(tmpFolder, "Project3");
                var solution1 = this.CreateSolution(tmpFolder, "Solution1", project1);
                var solution2 = this.CreateSolution(tmpFolder, "Solution2", project1, project2);

                var actual = VisualStudioHelper.GetVisualStudioSolutionFiles(tmpFolder, tmpFolder).ToArray();
                this.Assert(actual, new[]
                {
                    solution1, solution2, project3
                });
            }
        }
Пример #2
0
        private async Task FormatCodeAsync()
        {
            try
            {
                Document activeDocument = await VisualStudioHelper.GetActiveDocumentAsync();

                if (VisualStudioHelper.FileIsExcludedType(activeDocument.FilePath))
                {
                    return;
                }
                SyntaxNode root = await VisualStudioHelper.GetDocumentRootAsync(activeDocument);

                bool isCSharpDocument = root.Language == VisualStudioHelper.CSharpLanguageName;
                if (!isCSharpDocument)
                {
                    return;
                }

                var        longLineFormatter = new LongLineFormatter(CSharpenerConfigSettings.LengthOfLineToBreakOn);
                SyntaxNode formattedRoot     = longLineFormatter.Visit(root);

                Document newDocument = activeDocument.WithSyntaxRoot(formattedRoot);
                bool     success     = await VisualStudioHelper.ApplyDocumentChangesAsync(newDocument);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
 public void ThenCustomToolIsSet(string customTool, IList <GeneratedFile> files)
 {
     foreach (var testee in files)
     {
         VisualStudioHelper.GetCustomToolByFileName(testee.Name, projectName).Should().Be(customTool);
     }
 }
        private Task RefreshAvailableActions()
        {
            if (_selectedProject == null)
            {
                return(Task.FromResult(0));
            }

            _viewModel.IsLoading = true;
            _viewModel.Actions.Clear();
            var selectedProjectName = _selectedProject.Name;

            return(Task.Run(() =>
            {
                var classes = _selectedProject.GetClasses();
                foreach (CodeClass codeClass in classes)
                {
                    if (codeClass.IsDerivedFrom["Microsoft.AspNetCore.Mvc.Controller"])
                    {
                        var className = codeClass.Name;
                        var functions = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, vsCMElement.vsCMElementFunction, false);
                        foreach (CodeFunction function in functions)
                        {
                            var attributes = VisualStudioHelper.GetAllCodeElementsOfType(function.Attributes, vsCMElement.vsCMElementAttribute, false);
                            var parameters = VisualStudioHelper.GetAllCodeElementsOfType(function.Parameters, vsCMElement.vsCMElementParameter, false);
                            var parameterNames = new List <string>();
                            foreach (CodeParameter parameter in parameters)
                            {
                                parameterNames.Add(parameter.Name);
                            }

                            var functionName = function.Name;
                            if (parameterNames.Any())
                            {
                                functionName = functionName + "{" + string.Join(",", parameterNames) + "}";
                            }

                            foreach (CodeAttribute attribute in attributes)
                            {
                                if (_httpAttributeFullNames.Contains(attribute.FullName))
                                {
                                    ExecuteRequestToUi(() =>
                                    {
                                        _viewModel.Actions.Add(new ControllerActionViewModel
                                        {
                                            Application = selectedProjectName,
                                            Controller = className,
                                            Action = functionName,
                                            IsSelected = true,
                                            DisplayName = $"{className}/{functionName}"
                                        });
                                    });
                                }
                            }
                        }
                    }
                }

                ExecuteRequestToUi(() => _viewModel.IsLoading = false);
            }));
        }
        protected override string UnitTestProjectTemplatePath(Project sourceProject)
        {
            string templateName;
            var    projectLanguage = VisualStudioHelper.GetProjectLanguage(sourceProject);
            var    isCSharp        = projectLanguage == "CSharp";

            var projectTypeGuids = sourceProject.ProjectTypeGuids(serviceProvider).ToList();

            if (projectTypeGuids.Contains(GUID_WindowsStore81))
            {
                templateName = isCSharp ? "Microsoft.CS.WinRT.UnitTestLibrary" : "Microsoft.VisualBasic.WinRT.UnitTestLibrary";
            }
            else if (isCSharp && projectTypeGuids.Contains(GUID_WindowsPhoneApp81))  // No VB template for WPA81, have to fall back to a class library
            {
                templateName = "Microsoft.CS.WindowsPhoneApp.UnitTestApp";
            }
            else if (projectTypeGuids.Contains(GUID_UniversalWindows))
            {
                templateName = isCSharp ? "Microsoft.CSharp.UAP.UnitTestProject" : "Microsoft.VisualBasic.UAP.UnitTestProject";
            }
            else
            {
                templateName = isCSharp ? "Microsoft.CSharp.ClassLibrary" : "Microsoft.VisualBasic.Windows.ClassLibrary";
            }

            return(solution.GetProjectTemplate(templateName, projectLanguage));
        }
        // wraps GenerateRaw in a message pump so that Visual Studio
        // will display the nice "waiting" modal window...
        private int GenerateWithPump(string wszInputFilePath,
                                     //string bstrInputFileContents,
                                     string wszDefaultNamespace,
                                     IntPtr[] rgbOutputFileContents,
                                     out uint pcbOutput,
                                     IVsGeneratorProgress pGenerateProgress)
        {
            uint pcbOutput2 = 0;
            var rc = 0;
            string errMsg = null;

            VisualStudioHelper.PumpAction("Generating models...", "Please wait while Umbraco.ModelsBuilder generates models.", () =>
            {
                rc = GenerateRaw(wszInputFilePath,
                //bstrInputFileContents,
                wszDefaultNamespace,
                rgbOutputFileContents,
                out pcbOutput2,
                //pGenerateProgress,
                out errMsg);
            });

            // get value back
            pcbOutput = pcbOutput2;

            // handle error here - cannot do it in PumpAction - ComObject exception
            if (errMsg != null)
                VisualStudioHelper.ReportError(pGenerateProgress, errMsg);

            return rc;
        }
 public void GivenIChangeTheLine(IList <TemplateChanges> changes)
 {
     foreach (var change in changes)
     {
         VisualStudioHelper.ReplaceLineInProjectItem(this.t4Template, change.From, change.To);
     }
 }
Пример #8
0
        public void Migrate(string destinationDirectory)
        {
            var solutionDirectory = VisualStudioHelper.TryGetSolutionDirectoryInfo().FullName;

            if (string.IsNullOrEmpty(solutionDirectory))
            {
                ConsoleLogHelper.ShowInfoMessage("Solution directory has not been found.", ConsoleColor.Red);
                return;
            }

            ConsoleLogHelper.ShowInfoMessage("Yeoman migration started", ConsoleColor.White);
            ConsoleLogHelper.ShowInfoMessage($"Source: {solutionDirectory}", ConsoleColor.Cyan);
            ConsoleLogHelper.ShowInfoMessage($"Destination: {destinationDirectory}", ConsoleColor.Green);

            ConsoleLogHelper.ShowInfoMessage($"Copy solution", ConsoleColor.Blue);
            var numFilesCopied = FileHelper.CopyDirectory(solutionDirectory, destinationDirectory,
                                                          new [] { ".vs", "bin", "obj", ".git", "WhiteLabel.ConvertToYeoman" },
                                                          new [] { ".gitignore" });

            // Remove ConvertToYeoman project from solution
            ConsoleLogHelper.ShowInfoMessage($"Remove Yeoman project from solution", ConsoleColor.Blue);
            var solutionFile = VisualStudioHelper.TryGetSolutionFileInfo(destinationDirectory);

            VisualStudioHelper.RemoveProjectFromSolution(solutionFile, "support/WhiteLabel.ConvertToYeoman/WhiteLabel.ConvertToYeoman.csproj");

            ConsoleLogHelper.ShowInfoMessage($"Modify project files for Yeoman", ConsoleColor.Blue);
            FileHelper.ReplaceContent(new[] { ".sln", ".csproj" }, destinationDirectory, "WhiteLabel", "<%= title %>");
            FileHelper.ReplaceContent(new[] { ".csproj" }, destinationDirectory, "<UserSecretsId>9897f4ce-1dfd-4146-9ae5-8ac9f8a492ab</UserSecretsId>", $"<UserSecretsId>{Guid.NewGuid().ToString()}</UserSecretsId>");

            ConsoleLogHelper.ShowInfoMessage($"{numFilesCopied} files have been copied", ConsoleColor.Blue);
        }
Пример #9
0
        public void GivenTheScriptWithFollowingContentForAutomation(string filename, string templateContent)
        {
            this.currentTesteeFilePath = Path.Combine(this.pathTestEnvironment, filename);
            File.WriteAllText(this.currentTesteeFilePath, templateContent);
            this.t4TemplateContent = templateContent;

            this.t4Template = VisualStudioHelper.AddFileToProject(this.projectName, this.currentTesteeFilePath);
        }
Пример #10
0
        /// <summary>
        /// Creates an instance of <see cref="DTOEntity"/>.
        /// </summary>
        /// <param name="typeNode">Type node.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <param name="navigations">Entity navigations available.</param>
        public DTOEntity(XElement typeNode, GenerateDTOsParams genParams, List <EntityNavigation> navigations)
            : base(typeNode, genParams)
        {
            // Define Class Base Type (if exists)
            string entityBaseType = EdmxHelper.GetEntityBaseType(typeNode);

            if (string.IsNullOrWhiteSpace(entityBaseType) == false)
            {
                // Check if base type is going to be generated
                if (genParams.TypesToGenerateFilter.Contains(entityBaseType) == true)
                {
                    this.NameBaseDTO = Utils.ConstructDTOName(entityBaseType, genParams);
                }
            }

            #region Set IsAbstract

            if (typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract) != null)
            {
                string abstractValue = typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract).Value.ToLower();
                this.IsAbstract = (abstractValue == Resources.XmlBoolTrue);
            }

            #endregion Set IsAbstract

            #region Set Navigation Properties

            if (navigations != null)
            {
                IEnumerable <EntityNavigation> myNavigations = navigations.Where(a => a.DTOName == this.NameDTO);

                foreach (EntityNavigation entityNav in myNavigations)
                {
                    foreach (EntityNavigationProperty navProperty in entityNav.NavigationProperties)
                    {
                        // Add property only if target type is going to be generated
                        if (genParams.TypesToGenerateFilter.Contains(navProperty.EntityTargetName) == true)
                        {
                            if (genParams.AssociationType == AssociationType.KeyProperty &&
                                this.Properties.Exists(p => p.PropertyName == navProperty.Name))
                            {
                                VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                                  string.Format(Resources.Warning_PropertyNameConflict, this.Name, navProperty.Name, navProperty.EntityTargetName),
                                                                  genParams.TargetProject, null, null, null);
                            }
                            else
                            {
                                this.Properties.Add(new DTOClassProperty(
                                                        entityNav.NavigationPropertyNameEDMX, navProperty, genParams.DTOsServiceReady));
                            }
                        }
                    }
                }
            }

            #endregion Set Association Properties
        }
Пример #11
0
        public void GivenIChangeTheLine(IList <TemplateChanges> changes)
        {
            // EnvDTE Automation in .NET 5 can lost content of files
            VisualStudioHelper.RecoverTemplateIfCorrupted(this.currentTesteeFilePath, this.t4TemplateContent);

            foreach (var change in changes)
            {
                VisualStudioHelper.ReplaceLineInProjectItem(this.t4Template, change.From, change.To);
            }
        }
Пример #12
0
        internal void OpenFile(string file, int line)
        {
            EnvDTE80.DTE2 dte2 = null;
            dte2 = System.Runtime.InteropServices.Marshal.GetActiveObject(VisualStudioHelper.ToProgramId(_version)) as EnvDTE80.DTE2;
            dte2.MainWindow.Activate();

            EnvDTE.Window window = dte2.ItemOperations.OpenFile(file, EnvDTE.Constants.vsViewKindTextView);

            var selection = dte2.ActiveDocument.Selection as EnvDTE.TextSelection;

            selection?.GotoLine(line, true);
        }
Пример #13
0
        private async Task FormatAndSortCodeAsync()
        {
            try
            {
                Document activeDocument = await VisualStudioHelper.GetActiveDocumentAsync();

                if (VisualStudioHelper.FileIsExcludedType(activeDocument.FilePath))
                {
                    return;
                }

                SyntaxNode root = await VisualStudioHelper.GetDocumentRootAsync(activeDocument);

                bool isCSharpDocument = root.Language == VisualStudioHelper.CSharpLanguageName;
                if (!isCSharpDocument)
                {
                    return;
                }

                var        regionRemover = new RegionRemover();
                SyntaxNode regionRoot    = regionRemover.Visit(root);

                var        usingsPlacer = new UsingsPlacer();
                SyntaxNode usingsRoot   = usingsPlacer.ProcessUsings(regionRoot);

                string     fileName = Path.GetFileName(activeDocument.FilePath);
                var        fhf      = new FileHeaderFormatter();
                SyntaxNode fhfRoot  = fhf.AddHeader(usingsRoot, fileName);

                var        sorter     = new CSharpSorter();
                SyntaxNode sorterRoot = sorter.Visit(fhfRoot);

                var        accessModifier = new AccessLevelModifierFormatter();
                SyntaxNode accessRoot     = accessModifier.Visit(sorterRoot);

                var        newLineFormatter = new NewlineFormatter();
                SyntaxNode newLineRoot      = newLineFormatter.Visit(accessRoot);

                var        ebf     = new ExpressionBodiedFormatter();
                SyntaxNode ebfRoot = ebf.Visit(newLineRoot);

                Document newDocument = activeDocument.WithSyntaxRoot(ebfRoot);
                bool     success     = await VisualStudioHelper.ApplyDocumentChangesAsync(newDocument);

                await VisualStudioHelper.InvokeCommandAsync(VisualStudioHelper.RunDefaultCodeCleanup);

                await VisualStudioHelper.InvokeCommandAsync(VisualStudioHelper.FormatDocumentCommandName);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        public void GivenTheScriptModifiedByFollowingContent(string filename, string templateContent)
        {
            var file = Path.Combine(sourcePath, filename);

            VisualStudioHelper.RemoveFileFromProject(file);

            File.WriteAllText(file, templateContent);

            t4Template = VisualStudioHelper.AddFileToProject(
                projectName,
                file);
        }
Пример #15
0
            public VisualStudioJSLintProviderTestableBase()
            {
                this.Environment = VisualStudioHelper.GetCurrentEnvironment();

                var serviceProvider = new ServiceProvider(this.Environment as IOleServiceProvider);
                var assemblyName    = typeof(VisualStudioJSLintProviderIntegration).Assembly.GetName().Name;
                var projectFile     = string.Format(@"Specifications\{0}\{0}.csproj", assemblyName);

                this.Project      = this.Environment.Locate().ProjectByUniqueName(projectFile);
                this.SettingsPath = Path.Combine(Path.GetDirectoryName(this.Project.FullName), "JSLintNet.json");

                this.Instance = new VisualStudioJSLintProvider(serviceProvider, new JSLintErrorListProvider(serviceProvider));
            }
Пример #16
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
        /// <param name="progress">A provider for progress updates.</param>
        /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            VisualStudioHelper.Initialize(this);
            await InitializeConfigurationAsync();

            await FormatCodeFileCommand.InitializeAsync(this);

            await FormatAndSortCodeFileCommand.InitializeAsync(this);

            await BreakLongCodeLinesCommand.InitializeAsync(this);
        }
        public void GivenTheFileManager()
        {
            this.pathTestEnvironment =
                VisualStudioHelper.GetProjectDirectory("T4.FileManager.VisualStudio.AcceptanceCriteria");
            var pathSource = Path.Combine(pathTestEnvironment, "..\\..\\", "src\\");

            var fileManagerFromSource = Path.Combine(pathSource, "T4.FileManager.VisualStudio.ttinclude");
            var fileManagerForTest    = Path.Combine(this.pathTestEnvironment, "T4.FileManager.VisualStudio.ttinclude");

            File.Copy(fileManagerFromSource, fileManagerForTest, true);

            this.targetTestPath = this.pathTestEnvironment;
        }
        public void GivenTheFileManager()
        {
            var pathDestination =
                VisualStudioHelper.GetProjectDirectory("T4.FileManager.VisualStudio.AcceptanceCriteria");
            var pathSource = Path.Combine(pathDestination, "..\\..\\", "src\\T4.FileManager.VisualStudio");

            var fmSource = Path.Combine(pathSource, "T4.FileManager.VisualStudio.ttinclude");
            var fmDest   = Path.Combine(pathDestination, "T4.FileManager.VisualStudio.ttinclude");

            File.Copy(fmSource, fmDest, true);

            sourcePath     = pathDestination;
            targetTestPath = pathDestination;
        }
        /// <summary>
        /// The SolutionBrowseButton browses for the .sln file that
        /// contains all the project files.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SolutionBrowseButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Browse for the folder
                DialogHelper.ChooseSolutionFile(this.SolutionTextBox);

                // set the solution fileName
                string solutionFileName = this.SolutionTextBox.Text;

                // if the fileName exists
                if (!String.IsNullOrEmpty(solutionFileName))
                {
                    // if the parent form exists
                    if (this.ParentUpdateForm != null)
                    {
                        // turn on a wait cursor
                        this.ParentUpdateForm.Cursor = Cursors.WaitCursor;

                        // force everything to catch up
                        this.Refresh();
                        Application.DoEvents();
                    }

                    // Find a visual studio solution
                    this.VSSolution = VisualStudioHelper.FindSolution(solutionFileName);

                    // display the VSSolution
                    this.DisplayVSSolution();

                    // if the parent form exists
                    if (this.ParentUpdateForm != null)
                    {
                        // turn on a wait cursor
                        this.ParentUpdateForm.Cursor = Cursors.Default;

                        // force everything to catch up
                        this.Refresh();
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception error)
            {
                // create a message to show to the user
                string message = "There was an error reading your solution. The error thrown was:" + Environment.NewLine + error.ToString();
                string title   = "Visual Studio Update Failure";
                MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #20
0
        private void LaunchInternal(bool elevated)
        {
            var newFilename = Path.Combine(Path.GetTempPath(), DateTime.Now.ToString("yyyy-MM-dd_HHmmss")) + ".sln";

            new SaveSolutionCommand(_settings, newFilename, _settings.VisualStudioVersion, this).Execute();
            var exePath = VisualStudioHelper.GetVisualStudioExecutable(_settings.VisualStudioVersion);
            var psi     = new ProcessStartInfo(exePath, newFilename);

            if (elevated)
            {
                psi.Verb = "runas";
            }
            Process.Start(psi);
            Application.Current.MainWindow.WindowState = WindowState.Minimized;
        }
Пример #21
0
 public static void AfterTestRun()
 {
     VisualStudioHelper.CleanupFiles(new[]
     {
         "T4.FileManager.VisualStudio.AcceptanceCriteria.ExampleTestProject",
         "T4.FileManager.VisualStudio.AcceptanceCriteria"
     },
                                     new[]
     {
         ".tt",
         ".g.cs",
         ".g1.cs",
         ".info.json",
         ".txt"
     });
 }
        public static SuoDataJson Deserialize(Stream stream, VisualStudioHelper vsHelper)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            if (vsHelper == null)
            {
                throw new ArgumentNullException(nameof(vsHelper));
            }

            StreamReader sr      = new StreamReader(stream);
            string       jsonStr = sr.ReadToEnd();

            return(Deserialize(jsonStr, vsHelper));
        }
        public static SuoDataJson Deserialize(string jsonStr, VisualStudioHelper vsHelper)
        {
            if (vsHelper == null)
            {
                throw new ArgumentNullException(nameof(vsHelper));
            }

            Logger.Info($"Try to parse suo json: '{jsonStr}'");

            if (string.IsNullOrEmpty(jsonStr))
            {
                // If the file is empty return empty solution data
                Logger.Info("Got empty suo json string. Returning empty SuoDataJson");
                return(new SuoDataJson());
            }

            // At the moment there are two json formats.
            // The 'old' format and the new one.
            // The FileVersion property was introduced with the new format
            // Hence, a missing FileVersion indicates the old format.
            var obj         = JObject.Parse(jsonStr);
            int fileVersion = ((int?)obj["FileVersion"]).GetValueOrDefault();

            Logger.Info($"Suo json file version is '{fileVersion}'");

            try
            {
                if (fileVersion < 2)
                {
                    return(ParseOldJsonFormat(obj, vsHelper));
                }
                else
                {
                    var entries = JsonConvert.DeserializeObject <SuoDataJson>(jsonStr);
                    return(entries);
                }
            }
            catch (Exception e)
            {
                Logger.Warn($"Failed to parse suo json with exception: '{e}'");
                return(new SuoDataJson());
            }
        }
Пример #24
0
        /// <summary>
        /// Attach the generated files if the process is successful.
        /// </summary>
        public void AttachGeneratedFiles()
        {
            if (this.Errors.IsNullOrEmpty())
            {
                foreach (var file in _generatedFiles)
                {
                    FileHelper.TryMove(file.TempPath, file.Path);                     // -> override files
                }

                VisualStudioHelper.AddToProject(
                    _generatedFiles.Where(i => i.AddToProject).Select(f => f.Path),
                    (file) =>
                {
                    if (this.OnGeneratedFile != null)
                    {
                        this.OnGeneratedFile(this, new TextTemplatingEngineFileGeneratedEventArgs(file, true));
                    }
                });
            }
        }
        private static SuoDataJson ParseOldJsonFormat(JObject obj, VisualStudioHelper vsHelper)
        {
            var result = new SuoDataJson();

            foreach (var prop in obj.Properties())
            {
                var projectState = ProjectDataSerializer.ParseOldJsonFormat(prop.Value);

                var projectName  = prop.Name;
                var projectGuid  = vsHelper.ProjectGuidForProjetName(projectName);
                var enabledItems = from item in projectState.Items
                                   where item.Enabled
                                   select item.Id;

                result.ProjectArguments.Add(projectGuid, projectState);
                result.CheckedArguments.AddRange(enabledItems);
            }

            return(result);
        }
Пример #26
0
        private void Launch(bool elevated)
        {
            InternalSave(null);
            var exePath = VisualStudioHelper.GetVisualStudioExecutable(_settings.VisualStudioVersion);
            var psi     = new ProcessStartInfo(exePath, "\"" + FileName + "\"");

            if (elevated)
            {
                psi.Verb = "runas";
            }
            try {
                Process.Start(psi);
                Application.Current.MainWindow.WindowState = WindowState.Minimized;
            } catch (Win32Exception ex) {
                // if NativeErrorCode = 1223, the user cancelled the UAC dialog
                if (ex.NativeErrorCode != 1223)
                {
                    throw;
                }
            }
        }
Пример #27
0
        public bool DoWork()
        {
            using (var vsHelper = new VisualStudioHelper(_dte2Service))
            {
                if (!vsHelper.CanAccessPackageManifest())
                {
                    return(ReturnFailed("No package manifest found... \n"));
                }
                var sfn         = vsHelper.GetSelectedItemPath();
                var imageHelper = new ImageHelper(sfn);
                if (string.IsNullOrEmpty(sfn))
                {
                    return(ReturnFailed("No file selected, aborting... \n"));
                }

                var extension = Path.GetExtension(sfn);
                if (extension != ".png" && extension != ".svg")
                {
                    return(ReturnFailed("Unsupported file selected (only .png & .svg allowed), aborting... \n"));
                }

                _outputWindow.OutputString("Starting generation of images... \n");


                foreach (var tile in _tilesToGenerate)
                {
                    _outputWindow.OutputString("Generating " + tile.XmlName + "... \n");
                    foreach (var scaleFactor in tile.ScaleFactors)
                    {
                        var savePath = GenerateSavePath(tile, scaleFactor, sfn);
                        imageHelper.GenerateFile(tile, scaleFactor, savePath);
                        vsHelper.AddFileToProject(savePath);
                        vsHelper.AddTileToPackage(tile);
                    }
                }
                _outputWindow.OutputString("Saving project... \n");
            }
            return(true);
        }
Пример #28
0
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName == "EntitiesToDTOs.Connect.EntitiesToDTOs")
                {
                    // Initialize VisualStudioHelper class
                    VisualStudioHelper.Initialize(_applicationObject);

                    // Check that a Solution is open
                    if (VisualStudioHelper.IsSolutionOpen(_applicationObject))
                    {
                        // Show the main window of EntitiesToDTOs
                        var mainWin = new MainWindow(_applicationObject);
                        mainWin.ShowDialog();
                    }

                    handled = true;
                    return;
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Gets the enum types available.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List <EnumType> GetEnumTypes(GenerateDTOsParams parameters)
        {
            var enums = new List <EnumType>();

            foreach (XElement xEnum in EdmxHelper.GetEnumTypeNodes(parameters.EDMXDocument))
            {
                var enumType = new EnumType();
                enumType.Name = xEnum.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                XAttribute attrExternalType = xEnum.Attribute(EdmxNodeAttributes.EnumType_ExternalTypeName);
                if (attrExternalType != null)
                {
                    enumType.ExternalTypeName = attrExternalType.Value;

                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                      string.Format(Resources.Warning_ManuallyAddReferenceForEnum, enumType.ExternalTypeName),
                                                      parameters.TargetProject, null, null, null);
                }

                enums.Add(enumType);
            }

            return(enums);
        }
 public static void AfterTestRun()
 {
     VisualStudioHelper.CleanupFiles(
         new[] { "T4.FileManager.NetCore.AcceptanceCriteria.ExampleTestProject", "T4.FileManager.NetCore.AcceptanceCriteria" },
         new[] { ".tt", ".g.cs", ".g1.cs", ".info.json", ".txt", ".ttinclude", "*.Designer.cs", "*.resx" });
 }
Пример #31
0
		static Vs()
		{
			Helper = new VisualStudioHelper();
		}