Ejemplo n.º 1
0
        public GherkinLanguageService(IProjectScope projectScope, IVisualStudioTracer tracer, bool enableStepMatchColoring)
        {
            this.projectScope = projectScope;
            this.tracer = tracer;
            this.enableStepMatchColoring = enableStepMatchColoring && projectScope.StepSuggestionProvider != null;
            AnalyzingEnabled = projectScope.GherkinScopeAnalyzer != null;

            tracer.Trace("Language service created", "GherkinLanguageService");
        }
 private void AttachToProcess(int pid)
 {
     try
     {
         var processes = dte.Debugger.LocalProcesses;
         foreach (Process processToAttach in processes)
         {
             if (processToAttach.ProcessID == pid)
             {
                 processToAttach.Attach();
                 return;
             }
         }
         tracer.Trace("SpecRun process not found.", GetType().Name);
     }
     catch (Exception ex)
     {
         tracer.Trace("Error attaching to SpecRun process. " + ex, GetType().Name);
     }
 }
 public void Apply()
 {
     try
     {
         task();
     }
     catch (Exception exception)
     {
         tracer.Trace("Exception: " + exception, "DelegateTask");
     }
 }
Ejemplo n.º 4
0
        private void Initialize()
        {
            if (generatorFolder == null)
            {
                throw new InvalidOperationException("The RemoteAppDomainTestGeneratorFactory has to be configured with the Setup() method before initialization.");
            }

            AppDomainSetup appDomainSetup = new AppDomainSetup {
                ApplicationBase = generatorFolder
            };

            appDomainSetup.ShadowCopyFiles = "true";

            //set configuration for generator app domain to have assembly redirects
            var appConfigFile = Path.Combine(generatorFolder, "plugincompability.config");

            if (File.Exists(appConfigFile))
            {
                appDomainSetup.ConfigurationFile = appConfigFile;
            }

            appDomain = AppDomain.CreateDomain("AppDomainForTestGeneration", null, appDomainSetup);

            var testGeneratorFactoryTypeFullName = typeof(TestGeneratorFactory).FullName;

            Debug.Assert(testGeneratorFactoryTypeFullName != null);

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            var generatorFactoryObject = appDomain.CreateInstanceAndUnwrap(remoteGeneratorAssemblyName, testGeneratorFactoryTypeFullName);

            remoteTestGeneratorFactory = generatorFactoryObject as ITestGeneratorFactory;

            if (remoteTestGeneratorFactory == null)
            {
                throw new InvalidOperationException("Could not load test generator factory.");
            }

            usageCounter = new UsageCounter(LoseReferences);
            tracer.Trace("AppDomain for generator created", "RemoteAppDomainTestGeneratorFactory");
        }
        private void ProcessBindingsFromProjectItem(ProjectItem projectItem, IdeBindingSourceProcessor bindingSourceProcessor, List <ProjectItem> relatedProjectItems)
        {
            foreach (CodeClass codeClass in VsxHelper.GetClasses(projectItem))
            {
                CodeClass2 bindingClassIncludingParts = codeClass as CodeClass2;

                var parts = new List <CodeClass>();

                if (bindingClassIncludingParts == null)
                {
                    parts.Add(codeClass);
                }
                else
                {
                    parts.AddRange(bindingClassIncludingParts.Parts.OfType <CodeClass>());
                }

                // in Visual Studio 2017, CodeClass2.Parts is always empty, fall back to CodeClass2.Collection
                // https://github.com/dotnet/roslyn/issues/21074
                if (parts.Count == 0)
                {
                    parts.AddRange(bindingClassIncludingParts.Collection.OfType <CodeClass>());
                }

                var baseClass = GetBaseClass(codeClass);

                while (baseClass != null)
                {
                    tracer.Trace("Adding inherited bindings for class: " + baseClass.FullName, GetType().Name);
                    parts.Add(baseClass);
                    baseClass = GetBaseClass(baseClass);
                }

                // we need to use the class parts to grab class-related information (e.g. [Binding] attribute)
                // but we need to process the binding methods only from the current part, otherwise these
                // methods would be registered to multiple file paths, and the update tracking would not work

                relatedProjectItems.AddRange(parts.Select(SafeGetProjectItem).Where(pi => pi != null && pi != projectItem));
                ProcessCodeClass(codeClass, bindingSourceProcessor, parts.ToArray());
            }
        }
Ejemplo n.º 6
0
 private BindingSourceMethod CreateBindingSourceMethod(CodeFunction codeFunction, BindingSourceType bindingSourceType, IdeBindingSourceProcessor bindingSourceProcessor)
 {
     try
     {
         var filteredAttributes = codeFunction.Attributes.Cast <CodeAttribute2>().Where(attr => bindingSourceProcessor.CanProcessTypeAttribute(attr.FullName)).ToArray();
         return(bindingReflectionFactory.CreateBindingSourceMethod(codeFunction, bindingSourceType, filteredAttributes));
     }
     catch (Exception ex)
     {
         tracer.Trace("CreateBindingSourceMethod error: {0}", this, ex);
         return(null);
     }
 }
Ejemplo n.º 7
0
        private bool RunInCurrentContext(string fileName, bool debug)
        {
            try
            {
                IRunCommandsExecutor runCommandsExecutor = VsxHelper.ResolveMefDependency <IRunCommandsExecutor>(serviceProvider);

                if (debug)
                {
                    runCommandsExecutor.OnInvokeDebugTestsInContext(new HostContext(fileName));
                }
                else
                {
                    runCommandsExecutor.OnInvokeRunTestsInContext(new HostContext(fileName));
                }
                return(true);
            }
            catch (Exception ex)
            {
                tracer.Trace("test tool error: {0}", this, ex);
                return(false);
            }
        }
 private bool RunInCurrentContext(bool debug)
 {
     try
     {
         dte.ExecuteCommand(GetRunInCurrentContextCommand(debug));
         return(true);
     }
     catch (Exception ex)
     {
         tracer.Trace("test tool error: " + ex, GetType().Name);
         return(false);
     }
 }
        /// <summary>
        /// Receives a parsed file scope for the buffer.
        /// </summary>
        /// <param name="waitForLatest">If true, the caller is blocked until the most recent scope is produced.</param>
        /// <param name="waitForParsingSnapshot"></param>
        /// <param name="waitForResult">Specifies whether the call should try waiting for any result.</param>
        /// <returns>The parsed file scope.</returns>
        public IGherkinFileScope GetFileScope(bool waitForLatest = false, ITextSnapshot waitForParsingSnapshot = null, bool waitForResult = true)
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException("GherkinLanguageService");
            }

            //tracer.Trace("GetFileScope (waitForLatest: {0}, waitForParsingSnapshot: {1}, waitForResult: {2}", this, waitForLatest, waitForParsingSnapshot, waitForResult);

            if (!waitForResult && lastGherkinFileScope == null)
            {
                return(null);
            }

            if (lastGherkinFileScope == null)
            {
                waitForLatest = true;
            }

            if (waitForLatest)
            {
                if (lastRegisteredSnapshot == null)
                {
                    tracer.Trace("GetFileScope - waiting for first registered snapshot... caller: {0}", this, new StackFrame(1, false).GetMethod().Name);
                    while (lastRegisteredSnapshot == null)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(50));
                    }
                    tracer.Trace("GetFileScope - first registered snapshot received", this);
                }
                waitForParsingSnapshot = lastRegisteredSnapshot;
            }

            if (waitForParsingSnapshot != null)
            {
                int       counter = 0;
                const int i       = 10;
                while (counter < i &&
                       (lastGherkinFileScope == null || lastGherkinFileScope.TextSnapshot != waitForParsingSnapshot))
                {
                    if (counter == 0)
                    {
                        tracer.Trace("GetFileScope - waiting for expected snapshot... caller: {0}", this, new StackFrame(1, false).GetMethod().Name);
                    }
                    Thread.Sleep(TimeSpan.FromMilliseconds(50));
                    counter++;
                }
                if (counter >= i)
                {
                    tracer.Trace("GetFileScope - failed to receive expected snapshot, using an older one", this);
                }
                else if (counter > 0)
                {
                    tracer.Trace("GetFileScope - expected snapshot received", this);
                }
            }

            return(lastGherkinFileScope);
        }
        public bool RunFeatures(ProjectItem projectItem, bool debug)
        {
            var projectScope = (VsProjectScope)projectScopeFactory.GetProjectScope(projectItem.ContainingProject);

            if (!projectScope.FeatureFilesTracker.IsInitialized)
            {
                MessageBox.Show("The feature files are not analyzed yet. Please wait.",
                                "SpecFlow",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                tracer.Trace("Feature file tracker is not yet initialized.", GetType().Name);
                return(false);
            }

            string filter = string.Join(" | ", CollectPaths(projectScope, projectItem));

            if (string.IsNullOrEmpty(filter))
            {
                return(false);
            }
            return(RunTests(projectItem.ContainingProject, filter, debug));
        }
Ejemplo n.º 11
0
        public void OnPackageLoad(IdeIntegration ideIntegration)
        {
            IdeIntegration = ideIntegration;

            if (IsDevBuild)
            {
                tracer.Trace("Running on 'dev' version on {0}", this, ideIntegration);
            }

            var today  = DateTime.Today;
            var status = GetInstallStatus();

            if (!status.IsInstalled)
            {
                // new user
                if (ShowNotification(GuidanceNotification.AfterInstall))
                {
                    status.InstallDate      = today;
                    status.InstalledVersion = CurrentVersion;
                    status.LastUsedDate     = today;

                    UpdateStatus(status);
                    CheckFileAssociation();
                }
            }
            else if (status.InstalledVersion < CurrentVersion)
            {
                //upgrading user
                if (ShowNotification(GuidanceNotification.Upgrade))
                {
                    status.InstallDate      = today;
                    status.InstalledVersion = CurrentVersion;

                    UpdateStatus(status);
                    CheckFileAssociation();
                }
            }
        }
Ejemplo n.º 12
0
        public ITestRunnerGateway GetTestRunnerGateway()
        {
            TestRunnerTool testRunnerTool = integrationOptionsProvider.GetOptions().TestRunnerTool;

            try
            {
                return(container.Resolve <ITestRunnerGateway>(testRunnerTool.ToString()));
            }
            catch (Exception ex)
            {
                tracer.Trace("Unable to resolve test runner gateway: " + ex, GetType().Name);
                return(null);
            }
        }
Ejemplo n.º 13
0
        private bool RunInCurrentContext(string fileName, bool debug, int lineNumber = -1)
        {
            try
            {
                const string testWindowAssemblyName           = "Microsoft.VisualStudio.TestWindow, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
                const string testWindowInterfacesAssemblyName = "Microsoft.VisualStudio.TestWindow.Interfaces, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
                var          tIRunCommandsExecutor            = Type.GetType("Microsoft.VisualStudio.TestWindow.Controller.IRunCommandsExecutor, " + testWindowAssemblyName, true);
                var          tHostContext = Type.GetType("Microsoft.VisualStudio.TestWindow.Extensibility.Model.HostContext, " + testWindowInterfacesAssemblyName, true);

                var runCommandsExecutor = VsxHelper.ResolveMefDependency(serviceProvider, tIRunCommandsExecutor);
                var hostContext         = Activator.CreateInstance(tHostContext, fileName, lineNumber, -1);

                string methodNameToInvoke = debug ? "OnInvokeDebugTestsInContext" : "OnInvokeRunTestsInContext";

                var method = tIRunCommandsExecutor.GetMethod(methodNameToInvoke);
                method.Invoke(runCommandsExecutor, new[] { hostContext });
                return(true);
            }
            catch (Exception ex)
            {
                tracer.Trace("test tool error: {0}", this, ex);
                return(false);
            }
        }
Ejemplo n.º 14
0
        public virtual GeneratorInfo GetGeneratorInfo()
        {
            tracer.Trace("Discovering generator information...", "VsGeneratorInfoProvider");

            GeneratorConfiguration generatorConfiguration = GenGeneratorConfig();

            try
            {
                var generatorInfo = new GeneratorInfo
                {
                    UsesPlugins = generatorConfiguration.UsesPlugins
                };

                if (DetectFromConfig(generatorInfo, generatorConfiguration))
                {
                    return(generatorInfo);
                }

                if (DetectDirectGeneratorReference(generatorInfo))
                {
                    return(generatorInfo);
                }

                if (!DetectFromRuntimeReference(generatorInfo))
                {
                    tracer.Trace("Unable to detect generator path", "VsGeneratorInfoProvider");
                }

                return(generatorInfo);
            }
            catch (Exception exception)
            {
                tracer.Trace(exception.ToString(), "VsGeneratorInfoProvider");
                return(null);
            }
        }
        private SpecFlowConfigurationHolder GetConfigurationHolderFromFileContent(string configFileContent)
        {
            XmlDocument configDocument;

            try
            {
                configDocument = new XmlDocument();
                configDocument.LoadXml(configFileContent);

                return(new SpecFlowConfigurationHolder(configDocument.SelectSingleNode("/configuration/specFlow")));
            }
            catch (Exception ex)
            {
                tracer.Trace("Config load error: " + ex, "VsSpecFlowConfigurationReader");
                return(new SpecFlowConfigurationHolder());
            }
        }
Ejemplo n.º 16
0
        private void TriggerReferenceChange(object state)
        {
            if (filesChangedOnDisk.Count == 0)
            {
                return;
            }
            var filesChanged = filesChangedOnDisk.ToArray();

            foreach (var filePath in filesChanged)
            {
                try
                {
                    FindReference(filePath); //this is a dummy call to trigger the change event of VS (to avoid duplicated processing)
                }
                catch (Exception ex)
                {
                    tracer.Trace("Error during reference change triggering: {0}", this, ex);
                }
            }
        }
Ejemplo n.º 17
0
        public static void Trace(this IIdeTracer tracer, string messageFormat, object category, params object[] messageArgs)
        {
            string categoryMessage = category is string?category.ToString() : category is Type ? ((Type)category).Name : category.GetType().Name;

            tracer.Trace(string.Format(messageFormat, messageArgs), categoryMessage);
        }
Ejemplo n.º 18
0
        public bool QueryStatus(GherkinEditorContext editorContext, Guid pguidCmdGroup, OLECMD prgCmd)
        {
            if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                var vsStd97CmdId = (VSConstants.VSStd97CmdID)prgCmd.cmdID;
#if TRACE_VS_COMMANDS
                tracer.Trace("QueryStatus/VSStd97CmdID:{0}", this, vsStd97CmdId);
#endif
                switch (vsStd97CmdId)
                {
                case VSConstants.VSStd97CmdID.GotoDefn:
                    if (goToStepDefinitionCommand.CanGoToDefinition(editorContext))
                    {
                        return(true);
                    }
                    break;
                }
            }
            else if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                var vsStd2KCmdId = (VSConstants.VSStd2KCmdID)prgCmd.cmdID;
#if TRACE_VS_COMMANDS
                tracer.Trace("QueryStatus/VSStd2KCmdID:{0}", this, vsStd2KCmdId);
#endif
                switch (vsStd2KCmdId)
                {
                case VSConstants.VSStd2KCmdID.COMMENT_BLOCK:
                case VSConstants.VSStd2KCmdID.COMMENTBLOCK:
                case VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK:
                case VSConstants.VSStd2KCmdID.UNCOMMENTBLOCK:
                case VSConstants.VSStd2KCmdID.RENAME:
                    return(true);
                }
            }
            else if (pguidCmdGroup == GuidList.guidSpecFlowCmdSet)
            {
                var specFlowCmdSet = (SpecFlowCmdSet)prgCmd.cmdID;
#if TRACE_VS_COMMANDS
                tracer.Trace("QueryStatus/SpecFlowCmdSet:{0}", this, specFlowCmdSet);
#endif
                switch (specFlowCmdSet)
                {
                case SpecFlowCmdSet.RunScenarios:
                case SpecFlowCmdSet.DebugScenarios:
                    return(true);
                }
            }
            else if (pguidCmdGroup == ReSharperCommandGroups.CommandGroup)
            {
                var reSharperCmd = (ReSharperCommand)prgCmd.cmdID;
#if TRACE_VS_COMMANDS
                tracer.Trace("QueryStatus/ReSharperCommand:{0}", this, reSharperCmd);
#endif
                switch (reSharperCmd)
                {
                case ReSharperCommand.GotoDeclaration:
                    if (goToStepDefinitionCommand.CanGoToDefinition(editorContext))
                    {
                        return(true);
                    }
                    break;

                case ReSharperCommand.LineComment:
                    return(true);

                case ReSharperCommand.UnitTestRunContext:
                case ReSharperCommand.UnitTestDebugContext:
                    return(true);
                }
            }
#if TRACE_VS_COMMANDS
            else
            {
                tracer.Trace("QueryStatus/Other:{0} / {1}", this, pguidCmdGroup, prgCmd.cmdID);
            }
#endif

            return(false);
        }
Ejemplo n.º 19
0
 protected override bool OnValidationError(string messageFormat, params object[] arguments)
 {
     tracer.Trace(messageFormat, "Warning", arguments);
     return(base.OnValidationError(messageFormat, arguments));
 }
Ejemplo n.º 20
0
        public static StepMap LoadFromFile(string fileName, IIdeTracer tracer)
        {
            try
            {
                var serializer = new StepMapSetializer();

                using (var reader = new StreamReader(fileName, Encoding.UTF8))
                {
                    var stepMap = serializer.Deserialize(reader);

                    if (stepMap.FileVersion != CURRENT_VERSION)
                    {
                        tracer.Trace(string.Format("StepMap has wrong file version"), typeof(StepMap).Name);
                        return null;
                    }

                    if (stepMap.IntegrationVersion != GetIntegrationVersion())
                    {
                        tracer.Trace(string.Format("StepMap file is generated by another SpecFlow version."), typeof(StepMap).Name);
                        return null;
                    }

                    tracer.Trace(string.Format("StepMap with {0} feature files and {1} step definitions loaded", stepMap.FeatureFileCount, stepMap.StepDefinitionCount), typeof(StepMap).Name);

                    return stepMap;
                }
            }
            catch(Exception loadException)
            {
                tracer.Trace(string.Format("StepMap loading error: {0}", loadException), typeof(StepMap).Name);
                return null;
            }
        }
Ejemplo n.º 21
0
        public void SaveToFile(string fileName, IIdeTracer tracer)
        {
            try
            {
                string folder = Path.GetDirectoryName(fileName);
                Debug.Assert(folder != null);

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var serializer = new StepMapSetializer();

                string tempFileName = fileName + ".new";

                using (var writer = new StreamWriter(tempFileName, false, Encoding.UTF8))
                {
                    serializer.Serialize(writer, this);
                }

                File.Copy(tempFileName, fileName, true);
                File.Delete(tempFileName);

                tracer.Trace(string.Format("StepMap with {0} feature files and {1} step definitions saved", FeatureFileCount, StepDefinitionCount), GetType().Name);
            }
            catch (Exception saveException)
            {
                tracer.Trace(string.Format("StepMap saving error: {0}", saveException), typeof(StepMap).Name);
            }
        }