コード例 #1
0
            /// <summary>
            /// Initializes a new instance of the Data class.
            /// </summary>
            /// <param name="core">The StyleCop core instance.</param>
            /// <param name="codeProjects">The list of code projects to analyze.</param>
            /// <param name="resultsCache">The results cache.</param>
            /// <param name="context">The run context.</param>
            /// <param name="autoSaveMode">Indicates whether to auto-save the document back to the source, if autoFixMode is true.</param>
            /// <param name="ignoreResultsCache">True to ignore the results cache.</param>
            /// <param name="settingsPath">The path to the settings to use during analysis.</param>
            public Data(
                StyleCopCore core,
                IList <CodeProject> codeProjects,
                ResultsCache resultsCache,
                RunContext context,
                bool autoSaveMode,
                bool ignoreResultsCache,
                string settingsPath)
            {
                Param.AssertNotNull(core, "core");
                Param.AssertNotNull(codeProjects, "codeProjects");
                Param.Ignore(resultsCache);
                Param.Ignore(context);
                Param.Ignore(autoSaveMode);
                Param.Ignore(ignoreResultsCache);
                Param.Ignore(settingsPath);

                this.core               = core;
                this.projects           = codeProjects;
                this.cache              = resultsCache;
                this.context            = context;
                this.autoSaveMode       = autoSaveMode;
                this.ignoreResultsCache = ignoreResultsCache;
                this.settingsPath       = settingsPath;
            }
コード例 #2
0
        /// <summary>
        /// Initializes an add-in.
        /// </summary>
        public void InitializeAddIn()
        {
            m_customCore = new StyleCopCore();
            m_customCore.ViolationEncountered += OnCustomViolationEncountered;

            m_customNamingAnalyzer        = new CustomNamingRules();
            m_customLayoutAnalyzer        = new CustomLayoutRules();
            m_customDocumentationAnalyzer = new CustomDocumentationRules();

            InitializeCustomAnalyzer(
                m_parent.Core,
                m_customCore,
                Constants.NamingRulesAnalyzerId,
                m_customNamingAnalyzer);

            InitializeCustomAnalyzer(
                m_parent.Core,
                m_customCore,
                Constants.LayoutRulesAnalyzerId,
                m_customLayoutAnalyzer);

            InitializeCustomAnalyzer(
                m_parent.Core,
                m_customCore,
                Constants.DocumentationRulesAnalyzerId,
                m_customDocumentationAnalyzer);
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new instance of the PropertyDialog class.
        /// </summary>
        /// <param name="pages">The array of pages to display on the property control.</param>
        /// <param name="settingsFile">The file that contains the settings being edited.</param>
        /// <param name="id">A unique ID that describes this set of property pages.</param>
        /// <param name="core">The StyleCop core instance.</param>
        /// <param name="helpCallback">Callback method for help, or null for no help.</param>
        /// <param name="context">The context to the send to the property page control.</param>
        public PropertyDialog(
            IList <IPropertyControlPage> pages,
            WritableSettings settingsFile,
            string id,
            StyleCopCore core,
            Help helpCallback,
            params object[] context)
        {
            Param.Assert(pages != null && pages.Count > 0, "pages", "Cannot be null or empty");
            Param.Assert(settingsFile != null && settingsFile.Loaded, "settingsFile", "The settings file must be loaded.");
            Param.AssertValidString(id, "id");
            Param.AssertNotNull(core, "core");
            Param.Ignore(helpCallback);
            Param.Ignore(context);

            this.pages        = pages;
            this.settingsFile = settingsFile;
            this.id           = id;
            this.core         = core;
            this.helpCallback = helpCallback;
            this.context      = context;

            this.InitializeComponent();

            this.core.Registry.RestoreWindowPosition(this.id, this, this.Location, this.Size);
        }
コード例 #4
0
        private void Register(StyleCopCore core)
        {
            Dictionary <SourceAnalyzer, List <StyleCopRule> > analyzerRulesDictionary = StyleCopRule.GetRules(core);

            var configurableSeverityItems = new List <Tuple <PsiLanguageType, ConfigurableSeverityItem> >();

            foreach (KeyValuePair <SourceAnalyzer, List <StyleCopRule> > analyzerRule in analyzerRulesDictionary)
            {
                string analyzerName     = analyzerRule.Key.Name;
                string compoundItemName = string.Format(GroupTitleTemplate, analyzerName);

                foreach (StyleCopRule rule in analyzerRule.Value)
                {
                    string ruleName    = rule.RuleID + ": " + SplitCamelCase(rule.Name);
                    string highlightID = GetHighlightID(rule.RuleID);
                    ConfigurableSeverityItem severityItem = new ConfigurableSeverityItem(
                        highlightID,
                        compoundItemName,
                        "StyleCop",
                        ruleName,
                        rule.Description,
                        Severity.WARNING,
                        false,
                        false,
                        null,
                        null);
                    configurableSeverityItems.Add(Tuple.Create((PsiLanguageType)CSharpLanguage.Instance, severityItem));
                }
            }
            this.ConfigurableSeverityItems = configurableSeverityItems;
        }
コード例 #5
0
        /// <summary>
        /// Initializes a new instance of the Log class.
        /// </summary>
        /// <param name="core">The core instance.</param>
        public Log(StyleCopCore core)
        {
            Param.AssertNotNull(core, "core");

            object data = core.Registry.CUGetValue("Logging");

            if (data != null)
            {
                try
                {
                    int level = (int)data;
                    if (level > 0)
                    {
                        this.logLevel = StyleCopLogLevel.High;
                    }
                }
                catch (FormatException)
                {
                    // Do nothing here since data is registry is invalid.
                }
            }

            if (this.logLevel != StyleCopLogLevel.None)
            {
                this.listener = new Listener();
                Trace.Listeners.Add(this.listener);
            }
        }
コード例 #6
0
        /// <summary>
        /// Gets the rules.
        /// </summary>
        /// <param name="styleCopCore">
        /// The style cop core.
        /// </param>
        /// <returns>
        /// A Dictionary of all the StyleCop rules indexed by their <see cref="SourceAnalyzer"/>.
        /// </returns>
        public static Dictionary <SourceAnalyzer, List <StyleCopRule> > GetRules(StyleCopCore styleCopCore)
        {
            List <SourceAnalyzer> loadedAnalyzers = GetSourceAnalyzers(styleCopCore);
            Dictionary <SourceAnalyzer, List <StyleCopRule> > rulesDictionary = GetRules(loadedAnalyzers);

            return(rulesDictionary);
        }
コード例 #7
0
        public void MyTestInitialize()
        {
            try
            {
                // Creating a package will set the factory service provider.
                this.package = new StyleCopVSPackage();

                this.mockServiceProvider = new Mock <IServiceProvider>();

                // Creates a dummy violation (In visual studio the violation is displayed in Error List panel)
                this.violation = CreateDummyViolationInfo();

                Assert.IsNotNull(this.package, "this.package is null");

                PrivateObject actual = new PrivateObject(this.package, new PrivateType(typeof(StyleCopVSPackage)));
                StyleCopCore  core   = (StyleCopCore)actual.GetFieldOrProperty("Core");

                Assert.IsNotNull(core, "core is null");

                core.DisplayUI          = false;
                this.taskUnderTest      = new ViolationTask(this.package, this.violation, null);
                this.taskUnderTestShell = this.taskUnderTest;
            }
            catch (Exception ex)
            {
                // Use try catch to test a workaround on CI build (AppVeyor)
                Console.WriteLine(ex.Message);
            }
        }
コード例 #8
0
ファイル: AlertDialog.cs プロジェクト: kubiix/StyleCop
        /// <summary>
        /// Shows the alert dialog.
        /// </summary>
        /// <param name="core">
        /// The StyleCop core instance.
        /// </param>
        /// <param name="parent">
        /// The parent control.
        /// </param>
        /// <param name="message">
        /// The message to display on the dialog.
        /// </param>
        /// <param name="title">
        /// The title of the dialog.
        /// </param>
        /// <param name="buttons">
        /// The dialog buttons.
        /// </param>
        /// <param name="icon">
        /// The dialog icon.
        /// </param>
        /// <returns>
        /// Returns the dialog result.
        /// </returns>
        public static DialogResult Show(StyleCopCore core, Control parent, string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            Param.RequireNotNull(core, "core");
            Param.Ignore(parent);
            Param.RequireValidString(message, "message");
            Param.RequireValidString(title, "title");
            Param.Ignore(buttons);
            Param.Ignore(icon);

            if (core.DisplayUI)
            {
                return(DisplayMessageBox(parent, message, title, buttons, icon));
            }
            else
            {
                // Alert Dialogs which provide options other than OK cannot be handled when the
                // program is running in a non-UI mode.
                if (buttons != MessageBoxButtons.OK)
                {
                    throw new InvalidOperationException(Strings.AlertDialogWithOptionsInNonUIState);
                }

                SendToOutput(core, message, icon);
                return(DialogResult.OK);
            }
        }
コード例 #9
0
        /// <summary>
        /// Gets the rules.
        /// </summary>
        /// <param name="analyzer">
        /// The analyzer.
        /// </param>
        /// <returns>
        /// A list of all the rules for the <see cref="SourceAnalyzer"/>.
        /// </returns>
        private static List <StyleCopRule> GetRules(SourceAnalyzer analyzer)
        {
            XmlDocument         xmlDocument     = StyleCopCore.LoadAddInResourceXml(analyzer.GetType(), null);
            List <StyleCopRule> xmlDefinedRules = GetRulesFromXml(xmlDocument);

            return(xmlDefinedRules);
        }
コード例 #10
0
        /// <summary>
        /// Occurs when the <see cref="LaunchStyleCopButton"/> is clicked.
        /// </summary>
        /// <param name="sender">The <see cref="System.Object"/> that raised the event.</param>
        /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param>
        private void LaunchStyleCopButton_Click(object sender, EventArgs e)
        {
            string tempFileName = Path.GetTempFileName();

            try
            {
                // Write the existing settings to the file before creating the UI.
                File.WriteAllText(tempFileName, this.Settings.StyleCopSettings);

                StyleCopCore core = new StyleCopCore(null, null);
                core.Initialize(null, true);
                core.DisplayUI         = true;
                core.WriteResultsCache = false;

                if (core.ShowSettings(tempFileName))
                {
                    // Read the new settings from the file.
                    this.Settings.StyleCopSettings = File.ReadAllText(tempFileName);
                }
            }
            finally
            {
                // Destroy the temp file so remnants aren't left lying around.
                File.Delete(tempFileName);
            }
        }
コード例 #11
0
        /// <summary>
        /// Finds a linked settings document and merges it with the given settings.
        /// </summary>
        /// <param name="originalSettings">The original settings.</param>
        /// <param name="mergeOriginal">Indicates whether the merge the original settings with the linked settings.</param>
        /// <returns>Returns the merged settings.</returns>
        /// <remarks>This method is designed to work only in file-based environments.</remarks>
        private Settings FindMergedSettingsThroughLinkedSettings(Settings originalSettings, bool mergeOriginal)
        {
            Param.AssertNotNull(originalSettings, "originalSettings");
            Param.Ignore(mergeOriginal);

            StringProperty linkedSettingsProperty = originalSettings.GlobalSettings.GetProperty(SettingsMerger.LinkedSettingsProperty) as StringProperty;

            if (linkedSettingsProperty != null && !string.IsNullOrEmpty(linkedSettingsProperty.Value))
            {
                string linkedSettingsFile = Environment.ExpandEnvironmentVariables(linkedSettingsProperty.Value);

                if (linkedSettingsFile.StartsWith(".", StringComparison.Ordinal) || !linkedSettingsFile.Contains("\\"))
                {
                    linkedSettingsFile = StyleCopCore.MakeAbsolutePath(originalSettings.Location, linkedSettingsFile);
                }

                if (File.Exists(linkedSettingsFile))
                {
                    Settings mergedLinkedSettings = this.environment.GetSettings(linkedSettingsFile, true);
                    if (mergedLinkedSettings != null)
                    {
                        if (mergeOriginal)
                        {
                            return(MergeSettings(mergedLinkedSettings, originalSettings));
                        }

                        return(mergedLinkedSettings);
                    }
                }
            }

            // The linked settings do not exist. Just return the original settings.
            return(originalSettings);
        }
コード例 #12
0
ファイル: CodeFile.cs プロジェクト: longzai2651/StyleCop2
        /// <summary>
        /// Initializes a new instance of the CodeFile class.
        /// </summary>
        /// <param name="path">
        /// The path to the code file.
        /// </param>
        /// <param name="project">
        /// The project that contains this file.
        /// </param>
        /// <param name="parser">
        /// The parser that created this file object.
        /// </param>
        /// <param name="configurations">
        /// The list of configurations for the file.
        /// </param>
        public CodeFile(string path, CodeProject project, SourceParser parser, IEnumerable <Configuration> configurations)
            : base(project, parser, configurations)
        {
            Param.RequireNotNull(path, "path");
            Param.RequireNotNull(project, "project");
            Param.RequireNotNull(parser, "parser");
            Param.Ignore(configurations);

            // If this is not a full path, then we need to add the current directory.
            if (!path.StartsWith(@"\\", StringComparison.Ordinal) && path.Length >= 2 && path[1] != ':')
            {
                path = System.IO.Path.GetFullPath(path);
            }

            // BugFix 6777 - Update the path field after correcting the local path variable
            this.path   = path;
            this.name   = System.IO.Path.GetFileName(path);
            this.folder = StyleCopCore.CleanPath(System.IO.Path.GetDirectoryName(path));

            // Strip out the file extension.
            this.fileType = System.IO.Path.GetExtension(this.name).ToUpperInvariant();
            if (this.fileType.Length > 0)
            {
                this.fileType = this.fileType.Substring(1);
            }
        }
コード例 #13
0
ファイル: StyleCopRunnerInt.cs プロジェクト: icnocop/StyleCop
        /// <summary>
        /// Initializes a new instance of the <see cref="StyleCopRunnerInt"/> class.
        /// </summary>
        /// <param name="core">
        /// A reference to the core API
        /// </param>
        /// <param name="settings">
        /// A reference to the settings API
        /// </param>
        public StyleCopRunnerInt(StyleCopCore core, StyleCopSettings settings)
        {
            this.styleCopCore = core;
            this.styleCopSettings = settings;

            core.DisplayUI = true;
            core.ViolationEncountered += this.OnViolationEncountered;
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the AnalysisHelper class.
        /// </summary>
        /// <param name="serviceProvider">System service provider.</param>
        /// <param name="core">StyleCop engine.</param>
        internal AnalysisHelper(IServiceProvider serviceProvider, StyleCopCore core)
        {
            Param.AssertNotNull(serviceProvider, "serviceProvider");
            Param.AssertNotNull(core, "core");

            this.serviceProvider = serviceProvider;
            this.core = core;
        }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the AnalysisHelper class.
        /// </summary>
        /// <param name="serviceProvider">System service provider.</param>
        /// <param name="core">StyleCop engine.</param>
        internal AnalysisHelper(IServiceProvider serviceProvider, StyleCopCore core)
        {
            Param.AssertNotNull(serviceProvider, "serviceProvider");
            Param.AssertNotNull(core, "core");

            this.serviceProvider = serviceProvider;
            this.core            = core;
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StyleCopRunnerInt"/> class.
        /// </summary>
        /// <param name="core">
        /// A reference to the core API
        /// </param>
        /// <param name="settings">
        /// A reference to the settings API
        /// </param>
        public StyleCopRunnerInt(StyleCopCore core, StyleCopSettings settings)
        {
            this.styleCopCore     = core;
            this.styleCopSettings = settings;

            core.DisplayUI             = true;
            core.ViolationEncountered += this.OnViolationEncountered;
        }
コード例 #17
0
        public void AnalysisHelperConstructorTest()
        {
            IServiceProvider   serviceProvider = new MockServiceProvider();
            StyleCopCore       core            = new StyleCopCore();
            FileAnalysisHelper specificTarget  = new FileAnalysisHelper(serviceProvider, core);

            Assert.IsNotNull(specificTarget, "Unable to instantiate the AnalysisHelper class");
            Assert.IsNotNull(specificTarget.Core, "AnalysisHelper.Core was null");
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the AnalysisThread class.
        /// </summary>
        /// <param name="full">True if a full analysis should be performed.</param>
        /// <param name="projects">The collection of projects to analysis.</param>
        /// <param name="core">The StyleCop core object.</param>
        public AnalysisThread(bool full, IList<CodeProject> projects, StyleCopCore core)
        {
            Param.Ignore(full);
            Param.Assert(projects != null && projects.Count > 0, "projects", "The projects collection must not be empty.");
            Param.AssertNotNull(core, "core");

            this.full = full;
            this.projects = projects;
            this.core = core;
        }
コード例 #19
0
        /// <summary>
        /// Initializes the object instance.
        /// </summary>
        protected internal override void Initialize()
        {
            base.Initialize();

            StyleCopVSPackage package = this.ServiceProvider.GetService(typeof(StyleCopVSPackage)) as StyleCopVSPackage;
            Debug.Assert(package != null, "Unable to locate the package");

            this.core = package.Core;
            this.helper = package.Helper;
        }
コード例 #20
0
        /// <summary>
        /// Initializes a new instance of the AnalysisThread class.
        /// </summary>
        /// <param name="full">True if a full analysis should be performed.</param>
        /// <param name="projects">The collection of projects to analysis.</param>
        /// <param name="core">The StyleCop core object.</param>
        public AnalysisThread(bool full, IList <CodeProject> projects, StyleCopCore core)
        {
            Param.Ignore(full);
            Param.Assert(projects != null && projects.Count > 0, "projects", "The projects collection must not be empty.");
            Param.AssertNotNull(core, "core");

            this.full     = full;
            this.projects = projects;
            this.core     = core;
        }
コード例 #21
0
        /// <summary>
        /// Gets the source analyzers.
        /// </summary>
        /// <param name="styleCopCore">
        /// The style cop core.
        /// </param>
        /// <returns>
        /// The list of <see cref="SourceAnalyzer"/> for StyleCop.
        /// </returns>
        private static List <SourceAnalyzer> GetSourceAnalyzers(StyleCopCore styleCopCore)
        {
            List <SourceAnalyzer> analyzers = new List <SourceAnalyzer>();

            foreach (SourceParser parser in styleCopCore.Parsers)
            {
                analyzers.AddRange(parser.Analyzers);
            }

            return(analyzers);
        }
コード例 #22
0
        /// <summary>
        /// Initializes the object instance.
        /// </summary>
        protected internal override void Initialize()
        {
            base.Initialize();

            StyleCopVSPackage package = this.ServiceProvider.GetService(typeof(StyleCopVSPackage)) as StyleCopVSPackage;

            Debug.Assert(package != null, "Unable to locate the package");

            this.core   = package.Core;
            this.helper = package.Helper;
        }
コード例 #23
0
        private static AnalysisThread CreateAnalysisThread(bool isFull)
        {
            var core            = new StyleCopCore();
            var projects        = new List <CodeProject>();
            var mockCodeProject = new Mock <CodeProject>(MockBehavior.Strict);
            var codeProject     = new CodeProject(0, "test", new Configuration(new string[0]));

            projects.Add(codeProject);

            var target = new AnalysisThread(isFull, projects, core);

            return(target);
        }
コード例 #24
0
        private static AnalysisThread CreateAnalysisThread(bool isFull)
        {
            StyleCopCore       core            = new StyleCopCore();
            List <CodeProject> projects        = new List <CodeProject>();
            Mock <CodeProject> mockCodeProject = new Mock <CodeProject>();
            CodeProject        codeProject     = new CodeProject(0, "test", new Configuration(new string[0]));

            projects.Add(codeProject);

            AnalysisThread target = new AnalysisThread(isFull, projects, core);

            return(target);
        }
コード例 #25
0
ファイル: StyleCopRunnerInt.cs プロジェクト: sarvex/StyleCop
        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            this.file = null;

            if (this.styleCopCore != null)
            {
                this.styleCopCore.ViolationEncountered -= this.OnViolationEncountered;
            }

            this.styleCopCore = null;
            this.violationHighlights.Clear();
            this.violationHighlights = null;
        }
コード例 #26
0
        /// <summary>
        /// Initializes the add-in.
        /// </summary>
        /// <param name="styleCopCore">
        /// The StyleCop core instance.
        /// </param>
        /// <param name="initializationXml">
        /// The add-in's XML initialization document.
        /// </param>
        /// <param name="topMostType">
        /// Indicates whether the xml document comes from the top-most type in the
        /// add-in's type hierarchy.
        /// </param>
        /// <param name="isKnownAssembly">
        /// Indicates whether the add-in comes from a known assembly.
        /// </param>
        internal void Initialize(StyleCopCore styleCopCore, XmlDocument initializationXml, bool topMostType, bool isKnownAssembly)
        {
            Param.AssertNotNull(styleCopCore, "styleCopCore");
            Param.AssertNotNull(initializationXml, "parserXml");
            Param.Ignore(topMostType);
            Param.Ignore(isKnownAssembly);

            // Set the reference to the core instance.
            this.core = styleCopCore;

            // Parse the parser Xml.
            this.ImportInitializationXml(initializationXml, topMostType, isKnownAssembly);
        }
コード例 #27
0
    /// <summary>
    /// Initializes a new instance of the <see cref="StyleCopSettingsHandler"/> class.
    /// </summary>
    /// <param name="settingsFilePath">The path to the StyleCop settings file.</param>
    /// <param name="coreInstance">The StyleCop core instance.</param>
    internal StyleCopSettingsHandler(string settingsFilePath, StyleCopCore coreInstance)
    {
      Param.AssertValidString(settingsFilePath, "settingsFilePath");
      Param.AssertNotNull(coreInstance, "coreInstance");

      this.core = coreInstance;

      // Load the local settings.
      Exception exception = null;
      this.localSettings = this.core.Environment.GetWritableSettings(settingsFilePath, out exception);

      if (exception != null)
      {
        Gtk.MessageDialog messageDialog = new Gtk.MessageDialog(
          null,
          Gtk.DialogFlags.Modal,
          Gtk.MessageType.Error,
          Gtk.ButtonsType.Ok,
          string.Format(CultureInfo.CurrentUICulture, StaticStringResources.ProjectSettingsFileNotLoadedOrCreated, exception.Message));

        messageDialog.Title = StaticStringResources.Title;
        messageDialog.Run();
        messageDialog.Destroy();

        throw exception;
      }
      else if (this.localSettings != null)
      {
        if (string.Compare(settingsFilePath, this.core.Environment.GetDefaultSettingsPath(), true) == 0)
        {
          // We must use reflection at the moment to set the DefaultSettings property (in case it exists).
          PropertyInfo prop = this.localSettings.GetType().GetProperty("DefaultSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
          if (prop != null && prop.CanWrite)
          {
            prop.SetValue(this.localSettings, true, null);
          }
        }

        // Set the contents of the parent settings file.
        SettingsMerger merger = new SettingsMerger(this.localSettings, this.core.Environment);
        this.parentSettings = merger.ParentMergedSettings;
        this.mergedSettings = merger.MergedSettings;

        // Set up the settings comparer.
        this.settingsComparer = new SettingsComparer(this.localSettings, this.parentSettings);
      }
      else
      {
        throw new InvalidOperationException("StyleCop settings couldn't be loaded!");
      }
    }
コード例 #28
0
        /// <summary>
        /// Called when the edit linked settings file button is clicked.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void EditLinkedSettingsFileClicked(object sender, EventArgs e)
        {
            Param.Ignore(sender, e);

            if (string.IsNullOrEmpty(this.linkedFilePath.Text))
            {
                AlertDialog.Show(
                    this.tabControl.Core,
                    this,
                    Strings.EmptySettingsFilePath,
                    Strings.Title,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            else
            {
                string expandedPath = Environment.ExpandEnvironmentVariables(this.linkedFilePath.Text);

                if (expandedPath.StartsWith(".", StringComparison.Ordinal) || !expandedPath.Contains("\\"))
                {
                    expandedPath = StyleCopCore.MakeAbsolutePath(this.tabControl.LocalSettings.Location, expandedPath);
                }

                // Check if there is a file at the given path. Create the settings file if needed.
                if (!File.Exists(expandedPath))
                {
                    // Create a new settings file at the given path.
                    Exception exception;

                    Settings createdSettingsFile = this.tabControl.Core.Environment.GetWritableSettings(expandedPath, out exception);
                    if (createdSettingsFile == null)
                    {
                        AlertDialog.Show(
                            this.tabControl.Core,
                            this,
                            string.Format(CultureInfo.CurrentUICulture, Strings.CannotLoadSettingsFilePath, exception == null ? string.Empty : exception.Message),
                            Strings.Title,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);

                        expandedPath = null;
                    }
                }

                if (!string.IsNullOrEmpty(expandedPath))
                {
                    this.EditParentSettings(expandedPath, false);
                }
            }
        }
コード例 #29
0
ファイル: Settings.cs プロジェクト: longzai2651/StyleCop2
        /// <summary>
        /// Initializes a new instance of the Settings class.
        /// </summary>
        /// <param name="core">
        /// The StyleCop core instance.
        /// </param>
        /// <param name="location">
        /// The path to the settings document.
        /// </param>
        /// <param name="contents">
        /// The initial contents of the settings document.
        /// </param>
        /// <param name="writeTime">
        /// The time when the settings were last updated.
        /// </param>
        public Settings(StyleCopCore core, string location, XmlDocument contents, DateTime writeTime)
        {
            Param.RequireNotNull(core, "core");
            Param.Ignore(location);
            Param.Ignore(contents);
            Param.Ignore(writeTime);

            this.core      = core;
            this.location  = location;
            this.contents  = contents;
            this.WriteTime = writeTime;

            this.LoadSettingsDocument();
        }
コード例 #30
0
        /// <summary>
        /// Registers the rules. Do not put the contents of this method in the constructor.
        /// If you do *sometimes* the StyleCop object won't be loaded be the time you construct it.
        /// </summary>
        private void Init()
        {
            StyleCopCore core = new StyleCopCore();

            core.Initialize(new List <string>(), true);

            Dictionary <SourceAnalyzer, List <StyleCopRule> > analyzerRulesDictionary = StyleCopRule.GetRules(core);

            HighlightingSettingsManager highlightManager = HighlightingSettingsManager.Instance;

            // TODO Not sure how to get a configurable severity id with the settings store so default to warning for now
            //// var defaultSeverity = highlightManager.GetConfigurableSeverity(DefaultSeverityId, null);
            this.RegisterRuleConfigurations(highlightManager, analyzerRulesDictionary, Severity.WARNING);
        }
コード例 #31
0
        /// <summary>
        /// Registers the rules. Do not put the contents of this method in the constructor.
        /// If you do *sometimes* the StyleCop object won't be loaded be the time you construct it.
        /// </summary>
        private void Init()
        {
            StyleCopCore core = new StyleCopCore();

            core.Initialize(new List <string>(), true);

            Dictionary <SourceAnalyzer, List <StyleCopRule> > analyzerRulesDictionary = StyleCopRule.GetRules(core);

            HighlightingSettingsManager highlightManager = HighlightingSettingsManager.Instance;

            Severity defaultSeverity = highlightManager.GetConfigurableSeverity(DefaultSeverityId, null);

            this.RegisterRuleConfigurations(highlightManager, analyzerRulesDictionary, defaultSeverity);
        }
コード例 #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RalphJansen.StyleCopCheckInPolicy.Policy.StyleCopConsole"/> class.
        /// </summary>
        /// <param name="policySettingsPath">The path to the policy settings.</param>
        /// <param name="settings">The policy settings.</param>
        public StyleCopConsole(string policySettingsPath, PolicySettings settings)
        {
            this.PolicySettingsPath = policySettingsPath;
            this.Settings           = settings;

            StyleCopCore core = new StyleCopCore(new TfsCheckInPolicyEnvironment(), null);

            core.ViolationEncountered += new EventHandler <ViolationEventArgs>(this.VoilationEncounteredCallback);
            core.Initialize(null, true);
            core.WriteResultsCache = false;
            core.DisplayUI         = false;

            this.Core = core;
        }
コード例 #33
0
        /// <summary>
        /// Disposes the contents of the class.
        /// </summary>
        /// <param name="disposing">Indicates whether to dispose unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            Param.Ignore(disposing);

            if (disposing)
            {
                if (this.core != null)
                {
                    // Unregister for StyleCop events.
                    this.core.ViolationEncountered -= this.CoreViolationEncountered;
                    this.core.OutputGenerated      -= this.CoreOutputGenerated;
                    this.core = null;
                }
            }
        }
コード例 #34
0
 /// <summary>
 /// Initializes a new instance of the HighlightingRegistering class.
 /// </summary>
 /// <param name="settingsStore">The settings store.</param>
 /// <param name="fileSystemTracker">
 /// The file System Tracker.
 /// </param>
 public HighlightingRegistering(ISettingsStore settingsStore, IFileSystemTracker fileSystemTracker)
 {
     // TODO: We shouldn't be doing any of this at runtime, especially not on each load
     // Registering highlightings should happen declaratively
     // Create this instance directly, rather than use the pool, because the pool needs to
     // be per-solution, as it caches settings for files in the solution
     Lifetimes.Using(
         temporaryLifetime =>
     {
         // We don't really need the file system tracker - it's only used when we get
         // settings, which we don't do as part of highlighting initialisation
         StyleCopCore core = StyleCopCoreFactory.Create(temporaryLifetime, settingsStore, fileSystemTracker);
         this.Register(core);
     });
 }
コード例 #35
0
        /// <summary>
        /// Disposes the contents of the class.
        /// </summary>
        /// <param name="disposing">Indicates whether to dispose managed resources.</param>
        protected override void Dispose(bool disposing)
        {
            Param.Ignore(disposing);
            base.Dispose(disposing);

            if (disposing)
            {
                if (this.helper != null)
                {
                    this.helper.Dispose();
                    this.helper = null;
                }

                this.core = null;
            }
        }
コード例 #36
0
ファイル: ViolationTask.cs プロジェクト: jonthegiant/StyleCop
        /// <summary>
        /// Initializes a new instance of the ViolationTask class.
        /// </summary>
        /// <param name="serviceProvider">System service provider.</param>
        /// <param name="violation">The StyleCop violation that this task represents.</param>
        internal ViolationTask(IServiceProvider serviceProvider, ViolationInfo violation)
        {
            Param.AssertNotNull(serviceProvider, "serviceProvider");
            Param.Ignore(violation);

            this.violation = violation;
            this.Column = 0;
            this.Document = violation.File;
            this.Line = violation.LineNumber - 1;
            this.Text = violation.Description;
            this.ErrorCategory = TaskErrorCategory.Warning;

            StyleCopVSPackage package = serviceProvider.GetService(typeof(StyleCopVSPackage)) as StyleCopVSPackage;
            Debug.Assert(package != null, "Unable to locate the package");

            this.core = package.Core;
        }
コード例 #37
0
        /// <summary>
        /// Gets the rules.
        /// </summary>
        /// <param name="styleCopCore">
        /// The style cop core.
        /// </param>
        /// <returns>
        /// A Dictionary of all the StyleCop rules indexed by their <see cref="SourceAnalyzer"/>.
        /// </returns>
        public static Dictionary<SourceAnalyzer, List<StyleCopRule>> GetRules(StyleCopCore styleCopCore)
        {
            List<SourceAnalyzer> loadedAnalyzers = GetSourceAnalyzers(styleCopCore);
            Dictionary<SourceAnalyzer, List<StyleCopRule>> rulesDictionary = GetRules(loadedAnalyzers);

            return rulesDictionary;
        }
コード例 #38
0
 /// <summary>
 /// Dispose the specified disposing.
 /// </summary>
 /// <param name="disposing">If set to <c>true</c> disposing.</param>
 private void Dispose(bool disposing)
 {
   if (disposing && this.core != null)
   {
     // Unregister StyleCop events again.
     this.core.ViolationEncountered -= ProjectOperationsExtensions.StyleCopCoreViolationEncountered;
     this.core.OutputGenerated -= ProjectOperationsExtensions.StyleCopCoreOutputGenerated;
     this.core = null;
   }
 }
コード例 #39
0
        /// <summary>
        /// Gets the source analyzers.
        /// </summary>
        /// <param name="styleCopCore">
        /// The style cop core.
        /// </param>
        /// <returns>
        /// The list of <see cref="SourceAnalyzer"/> for StyleCop.
        /// </returns>
        private static List<SourceAnalyzer> GetSourceAnalyzers(StyleCopCore styleCopCore)
        {
            List<SourceAnalyzer> analyzers = new List<SourceAnalyzer>();

            foreach (SourceParser parser in styleCopCore.Parsers)
            {
                analyzers.AddRange(parser.Analyzers);
            }

            return analyzers;
        }
コード例 #40
0
        /// <summary>
        /// Creates the list of project files to be analyzed.
        /// </summary>
        /// <param name="core"><see cref="T:StyleCopCore">Core object</see> that hosts the environment.</param>
        /// <param name="type">The analyze type being performed.</param>
        /// <returns>Returns the list of projects.</returns>
        internal static IList<CodeProject> GetProjectList(StyleCopCore core, AnalysisType type)
        {
            Param.AssertNotNull(core, "core");
            Param.Ignore(type);

            // Create a list to store the list of code projects to be analyzed.
            List<CodeProject> codeProjects = new List<CodeProject>();

            DTE applicationObject = GetDTE();

            if (type == AnalysisType.Solution || type == AnalysisType.Project)
            {
                // Create a project enumerator for the correct VS project list.
                ProjectCollection enumerator = new ProjectCollection();

                if (type == AnalysisType.Solution)
                {
                    enumerator.SolutionProjects = applicationObject.Solution.Projects;
                }
                else
                {
                    enumerator.SelectedProjects = (System.Collections.IEnumerable)applicationObject.ActiveSolutionProjects;
                }

                // Enumerate through the VS projects.
                foreach (Project project in enumerator)
                {
                    if (project != null)
                    {
                        EnumerateProject(
                            project,
                            new ProjectInvoker(AddCodeProject),
                            new ProjectItemInvoker(AddFileToProject),
                            codeProjects,
                            null);
                    }
                }
            }
            else if (type == AnalysisType.Item || type == AnalysisType.Folder)
            {
                GetSelectedItemFiles(codeProjects);
            }
            else if (type == AnalysisType.File)
            {
                Document document = applicationObject.ActiveDocument;
                if (document != null)
                {
                    CodeProject codeProject = null;

                    string projectPath = GetProjectPath(document.ProjectItem.ContainingProject);
                    if (projectPath != null)
                    {
                        codeProject = new CodeProject(
                            projectPath.GetHashCode(),
                            projectPath,
                            GetProjectConfiguration(document.ProjectItem.ContainingProject));
                    }
                    else if (document.FullName != null && document.FullName.Length > 0)
                    {
                        codeProject = new CodeProject(
                            document.FullName.GetHashCode(),
                            Path.GetDirectoryName(document.FullName),
                            new StyleCop.Configuration(null));
                    }

                    if (codeProject != null)
                    {
                        core.Environment.AddSourceCode(codeProject, document.FullName, document);
                        codeProjects.Add(codeProject);
                    }
                }
            }
            else
            {
                Debug.Fail("Unknown analysis type requested.");
            }

            return codeProjects;
        }
コード例 #41
0
        /// <summary>
        /// Disposes the contents of the class.
        /// </summary>
        /// <param name="disposing">Indicates whether to dispose unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            Param.Ignore(disposing);

            if (disposing)
            {
                if (this.core != null)
                {
                    // Unregister for StyleCop events.
                    this.core.ViolationEncountered -= this.CoreViolationEncountered;
                    this.core.OutputGenerated -= this.CoreOutputGenerated;
                    this.core = null;
                }
            }
        }
コード例 #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StyleCopSettings"/> class.
 /// </summary>
 /// <param name="styleCopCore">
 /// The style cop core. 
 /// </param>
 public StyleCopSettings(StyleCopCore styleCopCore)
 {
     this.styleCopCore = styleCopCore;
 }
コード例 #43
0
        /// <summary>
        /// Determines whether the given file extension is known.
        /// </summary>
        /// <param name="fileExtension">The file extension to check.</param>
        /// <param name="core">The core instance.</param>
        /// <returns>Returns true if the file extension is known, false otherwise.</returns>
        private static bool IsKnownFileExtension(string fileExtension, StyleCopCore core)
        {
            Param.AssertNotNull(fileExtension, "fileExtension");
            Param.AssertNotNull(core, "core");

            if (fileExtension.Length > 0)
            {
                foreach (SourceParser parser in core.Parsers)
                {
                    foreach (string fileType in parser.FileTypes)
                    {
                        if (string.Equals(fileExtension, fileType, StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
コード例 #44
0
        /// <summary>
        /// Creates the list of project files to be analyzed.
        /// </summary>
        /// <param name="core"><see cref="T:StyleCopCore">Core object</see> that hosts the environment.</param>
        /// <param name="type">The analyze type being performed.</param>
        /// <param name="analysisFilePath">The path to the initial file we are analyzing.</param>
        /// <param name="analysisHelper">The analysis helper.</param>
        /// <returns>Returns the list of projects.</returns>
        internal static IList<CodeProject> GetProjectList(StyleCopCore core, AnalysisType type, out string analysisFilePath, AnalysisHelper analysisHelper)
        {
            Param.AssertNotNull(core, "core");
            Param.Ignore(type);

            // Create a list to store the list of code projects to be analyzed.
            List<CodeProject> codeProjects = new List<CodeProject>();

            DTE applicationObject = GetDTE();

            analysisFilePath = null;

            switch (type)
            {
                case AnalysisType.Project:
                case AnalysisType.Solution:
                    // Create a project enumerator for the correct VS project list.
                    ProjectCollection enumerator = new ProjectCollection();

                    if (type == AnalysisType.Solution)
                    {
                        enumerator.SolutionProjects = applicationObject.Solution.Projects;
                    }
                    else
                    {
                        enumerator.SelectedProjects = (IEnumerable)applicationObject.ActiveSolutionProjects;
                    }

                    // Enumerate through the VS projects.
                    foreach (Project project in enumerator)
                    {
                        // We continue if we know the project type or if its a misc item or a solution folder
                        if (project != null && (IsKnownProjectType(project, analysisHelper) ||
                            project.Kind == Constants.vsProjectKindMisc ||
                            project.Kind == Constants.vsProjectKindSolutionItems))
                        {
                            EnumerateProject(project, AddCodeProject, AddFileToProject, codeProjects, null);
                        }
                    }

                    break;

                case AnalysisType.Folder:
                case AnalysisType.Item:
                    analysisFilePath = GetSelectedItemFiles(codeProjects);
                    break;

                case AnalysisType.File:
                    var document = applicationObject.ActiveDocument;
                    if (document != null)
                    {
                        CodeProject codeProject = null;

                        string projectPath = GetProjectPath(document.ProjectItem.ContainingProject);
                        if (projectPath != null)
                        {
                            codeProject = new CodeProject(projectPath.GetHashCode(), projectPath, GetProjectConfiguration(document.ProjectItem.ContainingProject), TargetFrameworkVersion(document.ProjectItem.ContainingProject));
                        }
                        else if (!string.IsNullOrEmpty(document.FullName))
                        {
                            codeProject = new CodeProject(document.FullName.GetHashCode(), Path.GetDirectoryName(document.FullName), new StyleCop.Configuration(null));
                        }

                        if (codeProject != null)
                        {
                            // If this is a designer.cs file (and so a dependant of another file) then we need to add it but also its parent and siblings.
                            analysisFilePath = document.FullName;

                            var allFilesForProjectItem = GetAllFilesForProjectItem(document.ProjectItem);

                            foreach (var path in allFilesForProjectItem)
                            {
                                core.Environment.AddSourceCode(codeProject, path, null);
                            }

                            codeProjects.Add(codeProject);
                        }
                    }

                    break;
                default:
                    Debug.Fail("Unknown analysis type requested.");
                    break;
            }

            return codeProjects;
        }
コード例 #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StyleCopSettings"/> class.
 /// </summary>
 /// <param name="lifetime">
 /// The lifetime of the settings object.
 /// </param>
 /// <param name="styleCopCore">
 /// The style cop core.
 /// </param>
 /// <param name="fileSystemTracker">
 /// The file system tracker.
 /// </param>
 public StyleCopSettings(Lifetime lifetime, StyleCopCore styleCopCore, IFileSystemTracker fileSystemTracker)
 {
     this.lifetime = lifetime;
     this.styleCopCore = styleCopCore;
     this.fileSystemTracker = fileSystemTracker;
 }
コード例 #46
0
        /// <summary>
        /// Returns an array of <see cref="CodeProject"/> which are required to fulfill the
        /// StyleCopCore.Analyze(IList{CodeProject}) method contract to parse the
        /// current file.
        /// </summary>
        /// <param name="core">
        /// StyleCopCore which performs the Source Analysis.
        /// </param>
        /// <param name="projectFile">
        /// The project file we are checking.
        /// </param>
        /// <param name="document">
        /// The document.
        /// </param>
        /// <returns>
        /// Returns an array of <see cref="CodeProject"/>.
        /// </returns>
        public static CodeProject[] GetProjects(StyleCopCore core, IProjectFile projectFile, IDocument document)
        {
            StyleCopTrace.In(core);

            // TODO We should load the configuration values for the project not just DEBUG and TRACE
            Configuration configuration = new Configuration(new[] { "DEBUG", "TRACE" });

            IList<IProjectFile> projectFiles = GetAllFilesForFile(projectFile);

            CodeProject[] codeProjects = new CodeProject[projectFiles.Count];
            int i = 0;

            foreach (IProjectFile projectfile in projectFiles)
            {
                string path = projectfile.Location.FullPath;

                CodeProject codeProject = new CodeProject(projectfile.GetHashCode(), path, configuration);

                string documentTextToPass = i == 0 ? document.GetText() : null;
                core.Environment.AddSourceCode(codeProject, path, documentTextToPass);

                codeProjects[i++] = codeProject;
            }

            return StyleCopTrace.Out(codeProjects);
        }
コード例 #47
0
ファイル: StyleCopRunnerInt.cs プロジェクト: kjata30/StyleCop
        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            this.file = null;

            if (this.styleCopCore != null)
            {
                this.styleCopCore.ViolationEncountered -= this.OnViolationEncountered;
            }

            this.styleCopCore = null;
            this.violationHighlights.Clear();
            this.violationHighlights = null;
        }
コード例 #48
0
 /// <summary>
 /// Initializes a new instance of the FileAnalysisHelper class.
 /// </summary>
 /// <param name="serviceProvider">System service provider.</param>
 /// <param name="core">Source analysis engine.</param>
 internal FileAnalysisHelper(IServiceProvider serviceProvider, StyleCopCore core) : base(serviceProvider, core)
 {
     Param.AssertNotNull(serviceProvider, "serviceProvider");
     Param.AssertNotNull(core, "core");
 }
コード例 #49
0
        /// <summary>
        /// Registers the rules. Do not put the contents of this method in the constructor.
        /// If you do *sometimes* the StyleCop object won't be loaded be the time you construct it.
        /// TODO: I have no idea what this means...
        /// </summary>
        /// <param name="core">
        /// The core API
        /// </param>
        private void Init(StyleCopCore core)
        {
            Dictionary<SourceAnalyzer, List<StyleCopRule>> analyzerRulesDictionary = StyleCopRule.GetRules(core);

            HighlightingSettingsManager highlightManager = HighlightingSettingsManager.Instance;

            // TODO Not sure how to get a configurable severity id with the settings store so default to warning for now
            //// var defaultSeverity = highlightManager.GetConfigurableSeverity(DefaultSeverityId, null);
            this.RegisterRuleConfigurations(highlightManager, analyzerRulesDictionary, Severity.WARNING);
        }
        /// <summary>
        /// Adds the highlights.
        /// </summary>
        private void AddHighlights()
        {
            StyleCopCore core = new StyleCopCore();
            core.Initialize(new List<string>(), true);

            Dictionary<SourceAnalyzer, List<StyleCopRule>> analyzerRulesDictionary = StyleCopRule.GetRules(core);

            HighlightingSettingsManager highlightManager = HighlightingSettingsManager.Instance;

            AddDefaultOption();

            Severity defaultSeverity = highlightManager.GetConfigurableSeverity(DefaultSeverityId, null);

            this.RegisterRuleConfigurations(highlightManager, analyzerRulesDictionary, defaultSeverity);
        }