Beispiel #1
0
        /// <summary>
        /// Inicializa as dependências do software
        /// </summary>
        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
            OxyPlotModule.EnsureLoaded();
            OxyPlotModule.Initialize();

            //inicializa os serviços de código
            CodeAnalysisService.LoadDocument("");
        }
Beispiel #2
0
        void scintillaCodeView_DwellStart(object sender, ScintillaNET.ScintillaMouseEventArgs e)
        {
            var curpos    = this.PositionFromPoint(e.X, e.Y);
            int mappedPos = CodePositionMapper != null?CodePositionMapper(this.Text, curpos) : curpos;

            if (mappedPos < 0)
            {
                return;
            }

            string fullCode = GetCode == null ? this.Text : GetCode();

            if (mappedPos > fullCode.Length - 1)
            {
                this.CallTip.Hide();
                return;
            }

            var currentChar = fullCode[mappedPos];

            if (char.IsWhiteSpace(currentChar))
            {
                this.CallTip.Hide();
                return;
            }

            var callTipText = new CodeAnalysisService().GetCallTipTextAtPosition(fullCode, mappedPos);

            if (!string.IsNullOrWhiteSpace(callTipText))
            {
                this.CallTip.BackColor = Color.FromArgb(231, 232, 236);
                this.CallTip.ForeColor = Color.Black;
                this.Styles[ScintillaNET.StylesCommon.CallTip].Font = _callTipFont;

                if (callTipText.Length > 150 && callTipText.IndexOf('\n') < 0)
                {
                    var chars = callTipText.ToCharArray();
                    for (int i = 149; i < chars.Length; i++)
                    {
                        if (char.IsWhiteSpace(chars[i]))
                        {
                            chars[i] = '\n';
                            break;
                        }
                    }
                    callTipText = new string(chars);
                }
                this.CallTip.Show(callTipText, curpos);
            }
            else
            {
                this.CallTip.Hide();
            }
        }
Beispiel #3
0
        private void RunRulesAndVerifyResult(CodeAnalysisService service, Action <CodeAnalysisResult, string> verify)
        {
            CodeAnalysisResult analysisResult = service.Analyze(this.ModelForAnalysis);

            // Only considering analysis errors for now - might want to expand to initialization and suppression errors in the future
            this.DumpErrors(analysisResult.AnalysisErrors);

            string problemsString = this.DumpProblemsToString(analysisResult.Problems);


            verify(analysisResult, problemsString);
        }
Beispiel #4
0
        void _diagnosticTimer_Tick(object sender, EventArgs e)
        {
            if (this.IsDisposed)
            {
                _diagnosticTimer.Stop();
                return;
            }

            int offset = CodePositionMapper != null?CodePositionMapper(this.Text, 0) : 0;

            string fullCode = GetCode == null ? this.Text : GetCode();

            if (fullCode == string.Empty)
            {
                return;
            }

            var cas         = new CodeAnalysisService();
            var diagnostics = cas.GetDiagnostics(fullCode);

            this.Indicators.Reset();
            foreach (var d in diagnostics)
            {
                int start = d.Location.SourceSpan.Start - offset;
                if (start < 0)
                {
                    continue;
                }

                int length = d.Location.SourceSpan.IsEmpty ? 1 : d.Location.SourceSpan.Length;
                var r      = new Range(start, start + length, this);
                ScintillaNET.Indicator ind = null;

                if (d.Severity == DiagnosticSeverity.Error)
                {
                    ind       = this.Indicators[0];
                    ind.Style = IndicatorStyle.Squiggle;
                    ind.Color = Color.Red;
                }
                else if (d.Severity == DiagnosticSeverity.Info)
                {
                    ind       = this.Indicators[1];
                    ind.Style = IndicatorStyle.Plain;
                    ind.Color = Color.Green;
                }

                if (ind != null)
                {
                    r.SetIndicator(ind.Index);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// RunTest for multiple scripts.
        /// </summary>
        /// <param name="fullId">ID of the single rule to be run. All other rules will be disabled</param>
        /// <param name="verify">Action that runs verification on the result of analysis</param>
        public virtual void RunTest(string fullId, Action <CodeAnalysisResult, string> verify)
        {
            if (fullId == null)
            {
                throw new ArgumentNullException("fullId");
            }
            if (fullId == null)
            {
                throw new ArgumentNullException("verify");
            }

            this.CreateModelUsingTestScripts();

            CodeAnalysisService service = this.CreateCodeAnalysisService(fullId);

            this.RunRulesAndVerifyResult(service, verify);
        }
        public List <QueryResult> CompileAndRun(string code, string mode, TextWriter textWriter)
        {
            SyntaxTree syntaxTree  = CSharpSyntaxTree.ParseText(code);
            var        compilation = CodeAnalysisService.CreateCompilation(syntaxTree);

            using (var stream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(stream);

                if (result.Success)
                {
                    var    assembly = Assembly.Load(stream.GetBuffer());
                    Module module   = assembly.GetModules()[0];
                    if (module == null)
                    {
                        throw new Exception("Module is null");
                    }

                    Type mt = module.GetType("MongoSharp.Query.QueryExecutor");

                    if (mt == null)
                    {
                        throw new Exception("Type is null");
                    }

                    MethodInfo methInfo = mt.GetMethod("RunQuery");

                    if (methInfo == null)
                    {
                        throw new Exception("MethodInfo is null");
                    }

                    var results = (List <QueryResult>)methInfo.Invoke(null, new[] { textWriter });

                    return(results);
                }

                int lineNbr = GetCodeStartLineNumber(code) - 1;
                var errors  = (from x in result.Diagnostics
                               where x.Severity == DiagnosticSeverity.Error
                               select x).ToList();
                string text = errors.Aggregate("Compile error: ", (current, ce) => current + ("\r\n" + GetErrorText(ce, lineNbr)));

                throw new Exception(text);
            }
        }
Beispiel #7
0
        protected void InitTest(string ruleId)
        {
            var casFactory   = new CodeAnalysisServiceFactory();
            var ruleSettings = new CodeAnalysisRuleSettings()
            {
                new RuleConfiguration(ruleId)
            };

            ruleSettings.DisableRulesNotInSettings = true;

            var caSettings = new CodeAnalysisServiceSettings()
            {
                RuleSettings = ruleSettings
            };

            caService = casFactory.CreateAnalysisService(SqlServerVersion.Sql120, caSettings);
        }
        public List <Type> CompileModelCode(string code, string theNamespace)
        {
            var sb = new StringBuilder();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Linq;");
            sb.AppendLine("using MongoDB.Bson;");
            sb.AppendLine("using MongoDB.Bson.Serialization.Attributes;");
            sb.AppendLine("using MongoDB.Driver;");
            sb.AppendLine("using MongoDB.Driver.Linq;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using MongoSharp.Model;");
            code = sb.ToString() + "namespace " + theNamespace + " {\r\n" + code + "\r\n}";

            SyntaxTree syntaxTree  = CSharpSyntaxTree.ParseText(code);
            var        compilation = CodeAnalysisService.CreateCompilation(syntaxTree);

            using (var stream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(stream);

                if (result.Success)
                {
                    var    assembly = Assembly.Load(stream.GetBuffer());
                    Module module   = assembly.GetModules()[0];
                    if (module == null)
                    {
                        throw new Exception("Module is null");
                    }

                    List <Type> types = (from t in module.GetTypes()
                                         where t.IsClass && t.Namespace == theNamespace
                                         select t).ToList();
                    return(types);
                }
                else
                {
                    var errors = (from x in result.Diagnostics
                                  where x.Severity == DiagnosticSeverity.Error
                                  select x).ToList();
                    string text = errors.Aggregate("Compile error: ", (current, ce) => current + ("\r\n" + ce.GetMessage()));
                    throw new Exception(text);
                }
            }
        }
        async void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
        {
            try
            {
                codeService = CodeAnalysisService.LoadDocument(_editor.Document.Text);

                if (e.Text == "(")
                {
                    var p = await codeService.GetMethodSignature(_editor.CaretOffset - 2);

                    if (p != null)
                    {
                        _insightWindow         = new OverloadInsightWindow(_editor.TextArea);
                        _insightWindow.Closed += (s, a) => _insightWindow = null;

                        _insightWindow.Provider = new OverloadProvider(p);
                        _insightWindow.Show();
                        return;
                    }
                }
                if (await codeService.ShouldTriggerCompletion(_editor.CaretOffset))
                {
                    _completionWindow         = new CompletionWindow(_editor.TextArea);
                    _completionWindow.Closed += (o, args) => _completionWindow = null;

                    var data = await CodeAnalysisService.LoadDocument(_editor.Document.Text).GetCompletitionDataAt(_editor.CaretOffset);

                    if (data.Count == 0 || _completionWindow == null)
                    {
                        return;
                    }

                    foreach (var d in data)
                    {
                        _completionWindow.CompletionList.CompletionData.Add(d);
                    }

                    _completionWindow.StartOffset -= 1;

                    _completionWindow.Show();
                }
            }
            catch { }
        }
Beispiel #10
0
        /// <summary>
        /// Sets up the service and disables all rules except the rule you wish to test.
        ///
        /// If you want all rules to run then do not change the
        /// <see cref="CodeAnalysisRuleSettings.DisableRulesNotInSettings"/> flag, as it is set to "false" by default which
        /// ensures that all rules are run.
        ///
        /// To run some (but not all) of the built-in rules then you could query the
        /// <see cref="CodeAnalysisService.GetRules"/> method to get a list of all the rules, then set their
        /// <see cref="RuleConfiguration.Enabled"/> and other flags as needed, or alternatively call the
        /// <see cref="CodeAnalysisService.ApplyRuleSettings"/> method to apply whatever rule settings you wish
        ///
        /// </summary>
        private CodeAnalysisService CreateCodeAnalysisService(string ruleIdToRun)
        {
            CodeAnalysisServiceFactory factory = new CodeAnalysisServiceFactory();
            var ruleSettings = new CodeAnalysisRuleSettings()
            {
                new RuleConfiguration(ruleIdToRun)
            };

            ruleSettings.DisableRulesNotInSettings = true;
            CodeAnalysisService service = factory.CreateAnalysisService(this.ModelForAnalysis.Version, new CodeAnalysisServiceSettings()
            {
                RuleSettings = ruleSettings
            });

            this.DumpErrors(service.GetRuleLoadErrors());

            Assert.IsTrue(service.GetRules().Any((rule) => rule.RuleId.Equals(ruleIdToRun, StringComparison.OrdinalIgnoreCase)),
                          "Expected rule '{0}' not found by the service", ruleIdToRun);
            return(service);
        }
Beispiel #11
0
        private void DoAutoComplete(char c)
        {
            const int OFFSET = 0; //2 (old code)

            string fullCode = GetCode == null ? this.Text : GetCode();

            if (fullCode == string.Empty)
            {
                return;
            }

            int curpos = CodePositionMapper != null
                ? CodePositionMapper(this.Text, this.CurrentPos - OFFSET)
                : this.CurrentPos - OFFSET;

            if (curpos < 0)
            {
                return;
            }

            SymbolResult result         = new CodeAnalysisService().LookupSymbols(fullCode, curpos, c);
            var          completionList = result.GetAutoCompleteList();

            if (completionList.Any())
            {
                this.AutoComplete.Show(5, completionList);
            }
            var overloadList = result.GetOverLoadList();

            if (overloadList.Any())
            {
                this.CallTip.BackColor = Color.FromArgb(231, 232, 236);
                this.CallTip.ForeColor = Color.Black;
                this.Styles[ScintillaNET.StylesCommon.CallTip].Font = _callTipFont;

                var ol = new ScintillaNET.OverloadList(overloadList.ToArray());
                this.CallTip.ShowOverload(ol);
            }
        }
        private async void AnalyzeCodeSyntax()
        {
            dispatcherTimer.Stop();

            try
            {
                foldingStretegy.UpdateFoldings(foldingManager, _editor.Document);

                var errorService = ErrorService.GetService();
                errorService.Clear();


                var d = await CodeAnalysisService.LoadDocument(_editor.Document.Text).GetDiagnosticsAsync();

                var s = d.Select(x =>
                {
                    var cd    = new CompilationDiagnostic(x);
                    var line  = _editor.Document.GetLineByOffset(x.Location.SourceSpan.Start);
                    cd.Line   = line.LineNumber;
                    cd.Column = line.Length;
                    return(cd);
                });

                errorService.AddRange(s);

                textMarkerService.RemoveAll(m => true);

                foreach (var item in d)
                {
                    var         span = item.Location.SourceSpan;
                    ITextMarker m    = textMarkerService.Create(span.Start, span.Length);
                    m.MarkerTypes = TextMarkerTypes.SquigglyUnderline;
                    m.MarkerColor = item.Severity == DiagnosticSeverity.Error ? Colors.Red : Colors.LightGreen;
                    m.ToolTip     = item.ToString();
                }
            }
            catch { }
        }
        public void Create(ReportRequest request)
        {
            var fileName = Path.GetFileNameWithoutExtension(request.InputPath);

            #region Loading dacpac
            SendNotification($"Loading {request.FileName}.dacpac");
            var sw = Stopwatch.StartNew();

            //load the dacpac
            TSqlModel model = TSqlModel.LoadFromDacpac(
                request.InputPath
                , new ModelLoadOptions()
            {
                LoadAsScriptBackedModel = true,
                ModelStorageType        = Microsoft.SqlServer.Dac.DacSchemaModelStorageType.Memory
            });
            CodeAnalysisServiceFactory factory = new CodeAnalysisServiceFactory();
            CodeAnalysisService        service = factory.CreateAnalysisService(model);

            //surpress rules
            service.SetProblemSuppressor(request.Suppress);
            sw.Stop();
            SendNotification($"Loading {request.FileName}.dacpac complete, elapsed: {sw.Elapsed.ToString(@"hh\:mm\:ss")}");
            #endregion

            #region Running rules
            SendNotification("Running rules");
            sw = Stopwatch.StartNew();
            //process non-suppressed rules
            var result = service.Analyze(model);

            if (!result.AnalysisSucceeded)
            {
                foreach (var err in result.AnalysisErrors)
                {
                    SendNotification(err.Exception.Message, NotificationType.Error);
                }
                return;
            }
            sw.Stop();
            SendNotification($"Running rules complete, elapsed: {sw.Elapsed.ToString(@"hh\:mm\:ss")}");
            #endregion

            #region Writing report
            //create report object
            var report = new Report(
                request.Solution,
                GetIssueTypes(service.GetRules(), request.SuppressIssueTypes).ToList(),
                request.FileName,
                GetProblems(result.Problems).ToList());

            SendNotification("Writing report");
            sw = Stopwatch.StartNew();
            //write out the xml
            switch (request.ReportOutputType)
            {
            case ReportOutputType.XML:
                var outFileName = GetOutputFileName(request, request.ReportOutputType);
                SerializeReport(report, outFileName);
                var outDir   = GetOutputDirectory(request);
                var xlstPath = Path.Combine(outDir, "RulesTransform.xslt");
                if (!File.Exists(xlstPath))
                {
                    File.WriteAllText(xlstPath, Resources.RulesTransform);
                }

                var xPathDoc     = new XPathDocument(outFileName);
                var xslTransform = new XslCompiledTransform();
                using (var xmlWriter = new XmlTextWriter(Path.Combine(outDir, $"{request.FileName}.html"), null))
                {
                    xslTransform.Load(xlstPath);
                    xslTransform.Transform(xPathDoc, null, xmlWriter);
                }
                break;

            case ReportOutputType.CSV:
                SerializeReportToCSV(report, GetOutputFileName(request, request.ReportOutputType));
                break;

            default:
                SendNotification($"Invalid report type: {request.ReportOutputType}");
                break;
            }
            sw.Stop();
            SendNotification($"Writing report complete, elapsed: {sw.Elapsed.ToString(@"hh\:mm\:ss")}");
            #endregion


            SendNotification($"Done with {request.FileName}.dacpac");
        }
Beispiel #14
0
 protected void CleanTest()
 {
     caService = null;
 }
        /// <summary>
        /// Cria uma nova instância de TankProperties
        /// </summary>
        public TankProperties()
        {
            this.InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif



            _editor            = this.FindControl <TextEditor>("Editor");
            _editor.Background = Brushes.Transparent;
            _editor.Options.ConvertTabsToSpaces = true;
            _editor.Options.IndentationSize     = 4;
            _editor.ShowLineNumbers             = true;
            _editor.SyntaxHighlighting          = HighlightingManager.Instance.GetDefinition("C#");
            _editor.TextArea.TextEntered       += textEditor_TextArea_TextEntered;
            _editor.TextArea.TextEntering      += textEditor_TextArea_TextEntering;
            _editor.TextArea.TextInput         += TextArea_TextInput;
            _editor.TextArea.Initialized       += (s, a) => AnalyzeCodeSyntax();
            _editor.KeyUp += TextArea_KeyUp;
            _editor.TextArea.IndentationStrategy = new AvaloniaEdit.Indentation.CSharp.CSharpIndentationStrategy();

            _insightWindow = new OverloadInsightWindow(_editor.TextArea);

            _editor.FontFamily = GetPlatformFontFamily();

            _editor.TextArea.PointerMoved += TextArea_PointerMoved;

            foldingManager  = FoldingManager.Install(_editor.TextArea);
            foldingStretegy = new BraceFoldingStrategy();

            var textMarkerService = new TextMarkerService(_editor.Document);
            _editor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService);
            _editor.TextArea.TextView.LineTransformers.Add(textMarkerService);
            IServiceContainer services = _editor.Document.GetService <IServiceContainer>();
            if (services != null)
            {
                services.AddService(typeof(ITextMarkerService), textMarkerService);
            }
            this.textMarkerService = textMarkerService;



            this.AddHandler(PointerWheelChangedEvent, (o, i) =>
            {
                if (i.KeyModifiers != KeyModifiers.Control)
                {
                    return;
                }
                if (i.Delta.Y > 0)
                {
                    _editor.FontSize++;
                }
                else
                {
                    _editor.FontSize = _editor.FontSize > 1 ? _editor.FontSize - 1 : 1;
                }
            }, RoutingStrategies.Bubble, true);

            codeService = CodeAnalysisService.LoadDocument(_editor.Document.Text);

            UndoCommand = new CommandAdapter(true)
            {
                Action = (p) => _editor.Undo()
            };
            RedoCommand = new CommandAdapter(true)
            {
                Action = (p) => _editor.Redo()
            };
        }