Exemplo n.º 1
0
    public bool Execute()
    {
        var executingMessage = string.Format("Fody (version {0}) Executing", typeof(Processor).Assembly.GetName().Version);

        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(executingMessage, "", "Fody", MSMessageEnum.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger
        {
            BuildEngine = BuildEngine,
        };

        try
        {
            Inner();
            return(!Logger.ErrorOccurred);
        }
        catch (Exception exception)
        {
            Logger.LogError(exception.ToFriendlyString());
            return(false);
        }
        finally
        {
            var finishedMessage = string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds);
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(finishedMessage, "", "Fody", MSMessageEnum.High));
        }
    }
Exemplo n.º 2
0
    public bool Execute()
    {
        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(string.Format("Fody (version {0}) Executing", GetType().Assembly.GetName().Version), "", "Fody", Microsoft.Build.Framework.MessageImportance.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger(MessageImportance)
        {
            BuildEngine = BuildEngine,
        };

        try
        {
            Inner();
            return(!Logger.ErrorOccurred);
        }
        catch (Exception exception)
        {
            Logger.LogError(exception.ToFriendlyString());
            return(false);
        }
        finally
        {
            stopwatch.Stop();
            Logger.Flush();
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds), "", "Fody", Microsoft.Build.Framework.MessageImportance.High));
        }
    }
Exemplo n.º 3
0
        public void Execute_NoFiles_ReturnsTrue()
        {
            TreeNode root = new TreeNode("Root");

            using (_mocks.Unordered())
            {
                _buildEngine.LogMessageEvent(null);
                LastCall.IgnoreArguments().Repeat.Any();
                Expect.Call(_treeService.Root).Return(root).Repeat.Any();
                _generator.Generate(root);
                Expect.Call(_source.Ccu).Return(_ccu).Repeat.Any();
            }

            _task.BuildEngine       = _buildEngine;
            _task.Sources           = new ITaskItem[0];
            _task.ControllerSources = new ITaskItem[0];
            _task.ViewSources       = new ITaskItem[0];
            _task.Namespace         = "Eleutian.Empty";
            _task.OutputFile        = "SiteMap.generated.cs";

            _mocks.ReplayAll();
            Assert.IsTrue(_task.Execute());
            Assert.AreEqual("SiteMap.generated.cs", _task.GeneratedItems[0].ItemSpec);

            File.Delete(_task.OutputFile);
        }
Exemplo n.º 4
0
        public void log_a_debug_event_containing(string message, params object[] args)
        {
            if (build_engine == null)
            {
                return;
            }

            build_engine.LogMessageEvent(new BuildMessageEventArgs(
                                             string.Format(message, args),
                                             string.Empty,
                                             calling_task.GetType().Name,
                                             MessageImportance.Low));
        }
 /// <inheritdoc />
 /// <summary>
 /// Logs a message but with the importance changed to <see cref="F:Microsoft.Build.Framework.MessageImportance.Low" />.
 /// </summary>
 /// <param name="e"></param>
 public void LogMessageEvent(BuildMessageEventArgs e) => _buildEngine.LogMessageEvent(new BuildMessageEventArgs(
                                                                                          e.Subcategory,
                                                                                          e.Code,
                                                                                          e.File,
                                                                                          e.LineNumber,
                                                                                          e.ColumnNumber,
                                                                                          e.EndLineNumber,
                                                                                          e.EndColumnNumber,
                                                                                          e.Message,
                                                                                          e.HelpKeyword,
                                                                                          e.SenderName,
                                                                                          MessageImportance.Low, // Lowers the message importance
                                                                                          e.Timestamp));
Exemplo n.º 6
0
        public void LogMessageEvent(BuildMessageEventArgs e)
        {
            if (e.Importance != MessageImportance.High)
            {
                var interesting = new[]
                { "Unified primary", "chosen", "conflict", "Unified Dependency", "Could not resolve this reference" };

                if (interesting.Any(i => e.Message.Contains(i)) ||

                    (lastInterestingMessageIndent != null && e.Message.StartsWith(lastInterestingMessageIndent)) || lastInterestingMessageIndent == string.Empty)
                {
                    var importanceField = e.GetType()
                                          .GetField("importance", BindingFlags.NonPublic | BindingFlags.Instance);
                    Debug.WriteLine("^" + e.Message);
                    //_buildEngine.LogMessageEvent(new BuildMessageEventArgs("about to bump importance of message:" + e.Message, "B", e.SenderName,MessageImportance.High));

                    importanceField.SetValue(e, MessageImportance.High);
                    var indents = Regex.Match(e.Message, @"^(\s+)");
                    if (lastInterestingMessageIndent == null && indents.Success == false) //special condition, last message was interesting but had no indentation
                    {
                        lastInterestingMessageIndent = string.Empty;
                    }
                    else if (string.IsNullOrEmpty(lastInterestingMessageIndent) && indents.Success)
                    {
                        lastInterestingMessageIndent = indents.Groups[1].Value;
                        _buildEngine.LogMessageEvent(
                            new BuildMessageEventArgs(
                                "Setting indent bumping to length:" + indents.Groups[1].Value.Length.ToString(), "B",
                                "B", MessageImportance.High));
                    }
                }
                else
                {
                    Debug.WriteLine("_" + e.Message);
                    lastInterestingMessageIndent = null;
                }
            }

            _buildEngine.LogMessageEvent(e);
        }
Exemplo n.º 7
0
        public void LogInfo_Always_Works()
        {
            using (_mocks.Unordered())
            {
                Expect.Call(_task.BuildEngine).Return(_engine).Repeat.Any();
                _engine.LogMessageEvent(null);
                LastCall.IgnoreArguments();
            }

            _mocks.ReplayAll();
            _logger.LogInfo("Hello {0}!", "World");
            _mocks.VerifyAll();
        }
        /// <summary>
        /// Replays the provided binlog file in the current build engine
        /// </summary>
        public static void Replay(IBuildEngine engine, string filePath)
        {
            if (File.Exists(filePath))
            {
                var replaySource = new Microsoft.Build.Logging.BinaryLogReplayEventSource();

                replaySource.MessageRaised += (s, e) => engine.LogMessageEvent(e);
                replaySource.WarningRaised += (s, e) => engine.LogWarningEvent(e);
                replaySource.ErrorRaised   += (s, e) => engine.LogErrorEvent(e);

                replaySource.Replay(filePath);
            }
        }
Exemplo n.º 9
0
 internal static async Task LogMessageOrWriteToConsoleOut(this IBuildEngine be, String message)
 {
     if (be == null)
     {
         await Console.Out.WriteLineAsync(message);
     }
     else
     {
         be.LogMessageEvent(new BuildMessageEventArgs(
                                message,
                                null,
                                null,
                                MessageImportance.Normal
                                ));
     }
 }
Exemplo n.º 10
0
        public bool LogMessageFromText(string lineOfText,
                                       MessageImportance messageImportance)
        {
            if (lineOfText == null)
            {
                throw new ArgumentNullException("lineOfText");
            }

            BuildMessageEventArgs bmea = new BuildMessageEventArgs(
                lineOfText, helpKeywordPrefix,
                null, messageImportance);

            buildEngine.LogMessageEvent(bmea);

            return(true);
        }
Exemplo n.º 11
0
        public void TestMethod1()
        {
            MockRepository mock = new MockRepository();

            IBuildEngine engine = MockRepository.GenerateStub <IBuildEngine>();

            //engine.Expect(s => s.LogMessageEvent(Arg<BuildMessageEventArgs>.Is.Anything));
            //mock.ReplayAll();

            engine.Stub(s => s.LogMessageEvent(Arg <BuildMessageEventArgs> .Is.Anything)).IgnoreArguments().WhenCalled(x =>
            {
                var evt = x.Arguments[0] as BuildMessageEventArgs;
                Console.WriteLine(evt.Message);
            });

            engine.Stub(s => s.LogWarningEvent(Arg <BuildWarningEventArgs> .Is.Anything)).IgnoreArguments().WhenCalled(x =>
            {
                var evt = x.Arguments[0] as BuildWarningEventArgs;
                Console.WriteLine(evt.Message);
            });

            engine.Stub(s => s.LogErrorEvent(Arg <BuildErrorEventArgs> .Is.Anything)).IgnoreArguments().WhenCalled(x =>
            {
                var evt = x.Arguments[0] as BuildErrorEventArgs;
                Console.WriteLine(evt.Message);
            });

            engine.LogMessageEvent(new BuildMessageEventArgs("test", "test", "test", MessageImportance.High));
            //mock.VerifyAll();

            Assert.AreNotEqual("", Environment.GetEnvironmentVariable("VisualStudioVersion"));

            //engine.Stub(s => s.ProjectFileOfTaskNode).Return("hulla");

            var validator = new ValidateOfficeAppManifest();

            validator.BuildEngine       = engine;
            validator.ManifestFilePaths = new[] { @"C:\projects\kr-addin\OutlookAddin\bin\Debug\app.publish\OfficeAppManifests\OutlookAddinManifest.xml" };
            validator.WebProjectPaths   = new string[] { @"C:\projects\kr-addin\OutlookAddinWeb\OutlookAddinWeb.csproj" };
            validator.ProjectMode       = SharePointProjectMode.MailApp.ToString();
            Assert.IsNotNull(validator.Log);

            var res = validator.Execute();
        }
Exemplo n.º 12
0
        /// <summary>
        /// The send report message.
        /// </summary>
        /// <param name="eventArgs">
        /// The event args.
        /// </param>
        /// <param name="buildEngine">
        /// The build engine.
        /// </param>
        /// <param name="senderName">
        /// The sender name.
        /// </param>
        public static void SendDeploymentMangerMessage(
            DeploymentMangerMessageEventArgs eventArgs, IBuildEngine buildEngine, string senderName)
        {
            switch (eventArgs.ReportMessageType)
            {
            case DeploymentMangerMessageType.Information:
                buildEngine.LogMessageEvent(
                    new BuildMessageEventArgs(eventArgs.Message, String.Empty, senderName, MessageImportance.Normal));
                break;

            case DeploymentMangerMessageType.Warning:
                buildEngine.LogWarningEvent(
                    new BuildWarningEventArgs(
                        "Reporting",
                        eventArgs.Method,
                        buildEngine.ProjectFileOfTaskNode,
                        buildEngine.LineNumberOfTaskNode,
                        buildEngine.ColumnNumberOfTaskNode,
                        0,
                        0,
                        eventArgs.Message,
                        String.Empty,
                        senderName));
                break;

            case DeploymentMangerMessageType.Error:

                buildEngine.LogErrorEvent(
                    new BuildErrorEventArgs(
                        "Reporting",
                        eventArgs.Method,
                        buildEngine.ProjectFileOfTaskNode,
                        buildEngine.LineNumberOfTaskNode,
                        buildEngine.ColumnNumberOfTaskNode,
                        0,
                        0,
                        eventArgs.Message,
                        String.Empty,
                        senderName));
                break;
            }
        }
        public static bool LogMessage(IBuildEngine buildEngine, BuildMessageEventArgs args)
        {
            bool success = true;
            if (args.Importance == MessageImportance.High)
            {
                int index = 0;
                using (TextReader reader = new StringReader(args.Message))
                {
                    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    {
                        Match match = tsLintRegex.Match(line);
                        if (match.Success)
                        {
                            int lineNumber = int.Parse(match.Groups["LineNumber"].Value);
                            int columnNumber = int.Parse(match.Groups["ColumnNumber"].Value);
                            BuildErrorEventArgs errorArgs = new BuildErrorEventArgs(
                                string.Empty,
                                string.Empty,
                                match.Groups["FileName"].Value,
                                lineNumber,
                                columnNumber,
                                0,
                                0,
                                match.Groups["End"].Value,
                                string.Empty,
                                string.Empty);
                            buildEngine.LogErrorEvent(errorArgs);
                            success = false;
                            index++;
                            if (index == 100)
                            {
                                break;
                            }
                        }
                    }
                }
            }

            buildEngine.LogMessageEvent(args);
            return success;
        }
Exemplo n.º 14
0
        private void LogBuildEvent(IssueKind issueKind, string message, MessageImportance messageImportance, string code = null,
                                   string path = null, int startLine = 0, int startColumn = 0, int endLine = 0, int endColumn = 0)
        {
            switch (issueKind)
            {
            case IssueKind.Error:
                _buildEngine.LogErrorEvent(new BuildErrorEventArgs(
                                               null, code, path, startLine, startColumn, endLine, endColumn, message, code, ProductConstants.ToolName));
                break;

            case IssueKind.Warning:
                _buildEngine.LogWarningEvent(new BuildWarningEventArgs(
                                                 null, code, path, startLine, startColumn, endLine, endColumn, message, code, ProductConstants.ToolName));
                break;

            default:
                var formattedMessage = $"[{ProductConstants.ToolName}] {message}";
                _buildEngine.LogMessageEvent(new BuildMessageEventArgs(
                                                 null, code, path, startLine, startColumn, endLine, endColumn, formattedMessage, code, ProductConstants.ToolName, messageImportance));
                break;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Replays the provided binlog file in the current build engine
        /// </summary>
        public static void Replay(IBuildEngine engine, string filePath, TaskLoggingHelper log)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    var replaySource = new Microsoft.Build.Logging.BinaryLogReplayEventSource();

                    replaySource.MessageRaised += (s, e) => engine.LogMessageEvent(e);
                    replaySource.WarningRaised += (s, e) => engine.LogWarningEvent(e);
                    replaySource.ErrorRaised   += (s, e) => engine.LogErrorEvent(e);

                    replaySource.Replay(filePath);
                }
                catch (Exception e)
                {
                    var fileSize = File.Exists(filePath) ? new FileInfo(filePath).Length : -1;

                    log.LogWarning($"Failed to replay source generation controller build messages (path:{filePath}, size:{fileSize}) : {e}");
                }
            }
        }
Exemplo n.º 16
0
        protected override void WriteInternal(WriteStyle style, string value)
        {
            // TODO: How do we normalize this with the current design? Perhaps hold lines without a line end until we get one?

            // MSBuild ALWAYS is a "Writeline"
            value = value.Trim('\f', '\n', '\r');
            if (string.IsNullOrWhiteSpace(value))
            {
                return;
            }

            if (style.HasFlag(WriteStyle.Error))
            {
                LogError(value);
            }
            else if (style.HasFlag(WriteStyle.Critical))
            {
                LogWarning(value);
            }
            else
            {
                MessageImportance importance = MessageImportance.Normal;
                if (style.HasFlag(WriteStyle.Bold) || style.HasFlag(WriteStyle.Important))
                {
                    importance = MessageImportance.High;
                }

                BuildMessageEventArgs message = new BuildMessageEventArgs(
                    message: value,
                    helpKeyword: null,
                    senderName: _taskName,
                    importance: importance);

                _buildEngine.LogMessageEvent(message);
            }
        }
Exemplo n.º 17
0
 /// <inheritdoc cref="ISlnGenLogger.LogMessageHigh" />
 public void LogMessageHigh(string message, params object[] args) => _buildEngine.LogMessageEvent(new BuildMessageEventArgs(message, null, null, MessageImportance.High, DateTime.UtcNow, args));
Exemplo n.º 18
0
 public virtual void LogMessage(string message, int level)
 {
     BuildEngine.LogMessageEvent(new BuildMessageEventArgs(GetIndent() + PrependMessage(message), "", "Fody", (Microsoft.Build.Framework.MessageImportance)level));
 }
Exemplo n.º 19
0
 public static void Debug(this IBuildEngine engine, string message, string sender = default)
 {
     engine.LogMessageEvent(new BuildMessageEventArgs(message, null, (sender ?? nameof(TSBuild)), MessageImportance.Low));
 }
Exemplo n.º 20
0
        public async Task <Boolean> ExecuteAsync(IBuildEngine be)
        {
            const String PROCESS = "NuGetUtils.MSBuild.Exec.Perform";
            // Call process, deserialize result, set output properties.
            var tempFileLocation = Path.Combine(Path.GetTempPath(), $"NuGetUtilsExec_" + Guid.NewGuid());

            Boolean retVal;

            try
            {
                await be.LogProcessInvocationMessage(PROCESS);

                var startTime = DateTime.UtcNow;

                var returnCode = await this._processMonitor.CallProcessAndStreamOutputAsync(
                    PROCESS,
                    new PerformConfiguration <String>
                {
                    NuGetConfigurationFile     = this._initializationArgs.SettingsLocation,
                    RestoreFramework           = this._environment.ThisFramework,
                    RestoreRuntimeID           = this._environment.ThisRuntimeID,
                    SDKFrameworkPackageID      = this._environment.SDKPackageID,
                    SDKFrameworkPackageVersion = this._environment.SDKPackageVersion,
                    PackageID      = this._environment.PackageID,
                    PackageVersion = this._entrypoint.ExactPackageVersion,
                    MethodToken    = this._entrypointMethod.MethodToken,
                    AssemblyPath   = this._initializationArgs.AssemblyPath,

                    ProjectFilePath       = be?.ProjectFileOfTaskNode,
                    ShutdownSemaphoreName = NuGetUtilsExecProcessMonitor.CreateNewShutdownSemaphoreName(),
                    ReturnValuePath       = tempFileLocation,
                    InputProperties       = new JObject(
                        this._propertyInfos
                        .Where(kvp => !kvp.Value.IsOutput)
                        .Select(kvp =>
                    {
                        var valInfo = kvp.Value;
                        var val     = valInfo.Value;
                        return(new JProperty(kvp.Key, valInfo.GetInputPropertyValue()));
                    })
                        ).ToString(Formatting.None),
                },
                    this._cancellationTokenSource.Token,
                    be == null?default(Func <String, Boolean, Task>) : (line, isError) =>
                {
                    if (isError)
                    {
                        be.LogErrorEvent(new BuildErrorEventArgs(
                                             null,
                                             null,
                                             null,
                                             -1,
                                             -1,
                                             -1,
                                             -1,
                                             line,
                                             null,
                                             NuGetExecutionTaskFactory.TASK_NAME
                                             ));
                    }
                    else
                    {
                        be.LogMessageEvent(new BuildMessageEventArgs(
                                               line,
                                               null,
                                               null,
                                               MessageImportance.High
                                               ));
                    }
                    return(null);
                }
                    );

                await be.LogProcessEndMessage(PROCESS, startTime);

                if (returnCode.HasValue && File.Exists(tempFileLocation))
                {
                    using (var sReader = new StreamReader(File.Open(tempFileLocation, FileMode.Open, FileAccess.Read, FileShare.None), new UTF8Encoding(false, false), false))
                        using (var jReader = new JsonTextReader(sReader))
                        {
                            foreach (var tuple in (JObject.Load(jReader)) // No LoadAsync in 9.0.0.
                                     .Properties()
                                     .Select(p => (p, this._propertyInfos.TryGetValue(p.Name, out var prop) ? prop : null))
                                     .Where(t => t.Item2?.IsOutput ?? false)
                                     )
                            {
                                var jProp = tuple.p;
                                this._propertyInfos[jProp.Name].Value = tuple.Item2.GetOutputPropertyValue(jProp.Value);
                            }
                        }
                }

                retVal = returnCode.HasValue && returnCode.Value == 0;
            }
            catch
            {
                if (this._cancellationTokenSource.IsCancellationRequested)
                {
                    retVal = false;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (File.Exists(tempFileLocation))
                {
                    File.Delete(tempFileLocation);
                }
            }

            return(retVal);
        }
Exemplo n.º 21
0
 public void LogMessage(string format, params object[] args)
 {
     _buildEngine.LogMessageEvent(new BuildMessageEventArgs(string.Format(format, args), "Semiodesk", "OntologyGenerator", MessageImportance.Normal));
 }
Exemplo n.º 22
0
 public static void LogMessage(this IBuildEngine engine, string message, MessageImportance imp)
 {
     engine.LogMessageEvent(new BuildMessageEventArgs(message, "", "Avalonia", imp));
 }
 public void Info(string message, params object[] args)
 {
     _buildEngine.LogMessageEvent(new BuildMessageEventArgs(Format(message, args), "", _sender, MessageImportance.High));
 }
Exemplo n.º 24
0
 void Log(MessageImportance importance, String message)
 {
     buildEngine.LogMessageEvent(new BuildMessageEventArgs(message, null, null, importance));
 }
 public void LogInfo(string message)
 {
     buildEngine.LogMessageEvent(new BuildMessageEventArgs(PrependMessage(message), "", "SqlPersistenceTask", MessageImportance.Normal));
 }