예제 #1
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType,
                                                    object notificationEventArgs, out int statusCode, out string statusMessage,
                                                    out Microsoft.TeamFoundation.Common.ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            properties    = null;
            statusMessage = String.Empty;
            try
            {
                BuildUpdatedEvent updatedEvent = (BuildUpdatedEvent)notificationEventArgs;
                Build             build        = updatedEvent.Build;
                Log.Info($"ProcessEvent {notificationEventArgs.GetType().Name} for build {updatedEvent.BuildId} (Build Number : {updatedEvent.Build.BuildNumber}, Build Definition: {updatedEvent.Build.Definition.Name})");

                CiEvent ciEvent = CiEventUtils.ToCiEvent(build);
                if (notificationEventArgs is BuildStartedEvent)
                {
                    ciEvent.EventType = CiEventType.Started;
                    _pluginManager.GeneralEventsQueue.Add(ciEvent);
                }
                else if (notificationEventArgs is BuildCompletedEvent)
                {
                    ciEvent.EventType = CiEventType.Finished;
                    _pluginManager.HandleFinishEvent(ciEvent);
                }
            }
            catch (Exception e)
            {
                var msg = $"ProcessEvent {notificationEventArgs.GetType().Name} failed {e.Message}";
                Log.Error(msg, e);
                TeamFoundationApplicationCore.LogException(requestContext, msg, e);
            }
            return(EventNotificationStatus.ActionPermitted);
        }
        public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            properties    = null;
            statusMessage = string.Empty;
            try
            {
                if (notificationType == NotificationType.Notification && notificationEventArgs is CheckinNotification)
                {
                    var checkinNotification = notificationEventArgs as CheckinNotification;
                    if (ShouldMergeItemsIfNecessary(requestContext, checkinNotification))
                    {
                        var changeset = requestContext.GetChangeset(checkinNotification.Changeset);
                        if (changeset != null)
                        {
                            TfsTeamProjectCollection impersonatedCollection = requestContext.GetImpersonatedCollection(changeset.Committer);
                            MergeWorkItems(impersonatedCollection, changeset.ChangesetId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TeamFoundationApplicationCore.LogException("Inmeta.TFS.MergeWorkItemEventHandler encountered an exception", ex);
            }

            return(EventNotificationStatus.ActionPermitted);
        }
예제 #3
0
        public Task NotifyAsync(TeamFoundationRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            if (!notification.TargetUserNames.Any())
            {
                return(Task.FromResult(0));
            }

            var    config             = TfsNotificationRelaySection.Instance;
            string host               = bot.GetSetting("host", "127.0.0.1");
            int    port               = bot.GetIntSetting("port", 25);
            string fromAddress        = bot.GetSetting("fromAddress");
            string fromName           = bot.GetSetting("fromName");
            string subjectTextId      = bot.GetSetting("subjectTextId", "plaintext");
            bool   isHtml             = bot.GetSetting("isHtml") == "true";
            var    subjectTextElement = config.Texts.FirstOrDefault(t => t.Id == subjectTextId) ?? bot.Text;
            string subject            = notification.ToMessage(bot, subjectTextElement, s => s).First();

            var client = new SmtpClient(host, port);

            var message = new MailMessage();

            message.From            = new MailAddress(fromAddress, fromName, Encoding.UTF8);
            message.SubjectEncoding = Encoding.UTF8;
            message.Subject         = subject;
            message.IsBodyHtml      = isHtml;
            message.BodyEncoding    = Encoding.UTF8;
            message.Body            = string.Join(isHtml ? "<br/>": "\n", notification.ToMessage(bot, s => s));

            var identityService = requestContext.GetService <ITeamFoundationIdentityService>();

            foreach (var username in notification.TargetUserNames)
            {
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.AccountName, username);
                var email    = identityService.GetPreferredEmailAddress(requestContext, identity.TeamFoundationId);
                if (string.IsNullOrEmpty(email))
                {
                    string errmsg = $"TfsNotificationRelay.Smtp.SmtpNotifier: User {username} doesn't have an email address.";
                    TeamFoundationApplicationCore.Log(requestContext, errmsg, 0, EventLogEntryType.Warning);
                }
                else
                {
                    message.To.Add(email);
                }
            }

            if (message.To.Any())
            {
                requestContext.Trace(0, TraceLevel.Info, Constants.TraceArea, "SmtpNotifier",
                                     string.Format("Sending {0} email notification to: {1}.", notification.GetType(), string.Join(", ", message.To.Select(m => m.Address))));

                return(client.SendMailAsync(message));
            }
            else
            {
                requestContext.Trace(0, TraceLevel.Warning, Constants.TraceArea, "SmtpNotifier",
                                     string.Format("No recipients to send {0} email notification to.", notification.GetType()));

                return(Task.FromResult(0));
            }
        }
예제 #4
0
        internal static void Log(string message, EventLogEntryType level = EventLogEntryType.Information)
        {
            TeamFoundationApplicationCore.Log(message, 9999, level);

            if (PluginConfiguration.Instance.HasLog)
            {
                File.AppendAllText(PluginConfiguration.Instance.LogFile, message + Environment.NewLine);
            }
        }
예제 #5
0
        //public const string EventLog = "Application";

        internal static void LogStart(string message)
        {
            TeamFoundationApplicationCore.Log(message, 9999, EventLogEntryType.Information);

            if (PluginConfiguration.Instance.HasLog)
            {
                File.AppendAllText(PluginConfiguration.Instance.LogFile,
                                   string.Format("At {0}{1}  {2}{1}"
                                                 , DateTime.Now, Environment.NewLine, message));
            }
        }
예제 #6
0
        internal static void LogDenied(string reasonMessage)
        {
            TeamFoundationApplicationCore.Log(reasonMessage, 9999, EventLogEntryType.Warning);

            EventLog.WriteEntry(EventLogSource, reasonMessage, EventLogEntryType.Warning, 1002);

            if (PluginConfiguration.Instance.HasLog)
            {
                File.AppendAllText(PluginConfiguration.Instance.LogFile,
                                   string.Format("At {0}{1}  Request DENIED: {2}{1}"
                                                 , DateTime.Now, Environment.NewLine, reasonMessage));
            }
        }
예제 #7
0
 public static void LogToFile(string logMessage)
 {
     try
     {
         FileStream   stream     = new FileStream("D:\\TFS_Log.txt", FileMode.OpenOrCreate);
         StreamWriter fileWriter = new StreamWriter(stream);
         fileWriter.WriteLine(logMessage);
         fileWriter.Close();
         stream.Close();
     }
     catch (Exception ex)
     {
         TeamFoundationApplicationCore.LogException("Logging to text file failed", ex);
     }
 }
예제 #8
0
        internal static void LogException(Exception ex)
        {
            TeamFoundationApplicationCore.LogException(ex.Message, ex);

            EventLog.WriteEntry(EventLogSource, ex.Message, EventLogEntryType.Error, 1001);

            if (PluginConfiguration.Instance.HasLog)
            {
                var lines = new List <string>();

                lines.Add("Exception: " + ex.Message);
                lines.Add(ex.StackTrace);

                File.AppendAllLines(PluginConfiguration.Instance.LogFile, lines);
            }
        }
예제 #9
0
        internal static void LogEvent(TeamFoundationRequestContext requestContext, string message, LogEventInformationLevel informationLevel)
        {
            switch (informationLevel)
            {
            case LogEventInformationLevel.Information:
                TeamFoundationTrace.Info(message);
                break;

            case LogEventInformationLevel.Warning:
                TeamFoundationTrace.Warning(message);
                TeamFoundationApplicationCore.Log(requestContext, message, TeamFoundationEventId.WarehouseErrorsBaseEventId, System.Diagnostics.EventLogEntryType.Warning);
                break;

            case LogEventInformationLevel.Error:
                TeamFoundationTrace.Error(message);
                TeamFoundationApplicationCore.Log(requestContext, message, TeamFoundationEventId.WarehouseErrorsBaseEventId, System.Diagnostics.EventLogEntryType.Error);
                break;
            }
        }
예제 #10
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext,
                                                    NotificationType notificationType, object notificationEventArgs,
                                                    out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            statusMessage = string.Empty;
            properties    = null;

            if (notificationType == NotificationType.Notification)
            {
                try
                {
                    if (notificationEventArgs is CheckinNotification)
                    {
                        var           notification = notificationEventArgs as CheckinNotification;
                        StringBuilder logMessage   = new StringBuilder();
                        logMessage.Append("\n***************************************\r\n");
                        logMessage.Append("New Check-in Done, Change set Details:-\r\n");
                        logMessage.AppendFormat("ChangeSet Id:{0}\r\n", notification.Changeset);
                        logMessage.AppendFormat("ChangeSet Description:{0}\r\n", notification.Comment);
                        logMessage.AppendFormat("Checked-in User:{0}\r\n", notification.ChangesetOwner.DistinctDisplayName);
                        logMessage.AppendFormat("Machine Name:{0}\r\n", notification.ComputerName);
                        logMessage.AppendFormat("Associated Work Items:{0}\r\n", notification.NotificationInfo.WorkItemInfo.Length);
                        StringBuilder workitems = new StringBuilder();
                        if (notification.NotificationInfo.WorkItemInfo.Length > 0)
                        {
                            for (int workitemindex = 0; workitemindex < notification.NotificationInfo.WorkItemInfo.Length; workitemindex++)
                            {
                                workitems.AppendFormat("{0},", notification.NotificationInfo.WorkItemInfo[0].Id);
                            }
                        }
                        logMessage.Append("\n***************************************");
                        VersionControlLogger.LogToFile(logMessage.ToString());
                    }
                }
                catch (Exception e)
                {
                    TeamFoundationApplicationCore.LogException("logger failed", e);
                }
            }
            return(EventNotificationStatus.ActionPermitted);
        }
예제 #11
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            requestContext.MapAndLoadCustomConfig();

            statusCode    = 0;
            properties    = null;
            statusMessage = String.Empty;
            var logMessage = "New Changeset was checked in by {0}. ID: {1}, comments: {2}";

            try
            {
                if (notificationType == NotificationType.Notification && notificationEventArgs is CheckinNotification)
                {
                    var checkinNotification = notificationEventArgs as CheckinNotification;

                    var checkinNotificationModel = checkinNotification.ToCheckinNotificationModel(requestContext);

                    if (checkinNotificationModel.ContainsValidJiraIssueId())
                    {
                        TeamFoundationApplicationCore.Log(
                            message: string.Format(logMessage, checkinNotificationModel.AuthorName, checkinNotificationModel.ChangesetId, checkinNotificationModel.Comment),
                            eventId: 123,
                            level: System.Diagnostics.EventLogEntryType.Information);

                        var jiraLinkRequests = checkinNotificationModel.CreateJiraIssueLinkRequests();

                        foreach (var request in jiraLinkRequests)
                        {
                            jiraIssueRemoteLinkService.CreateRemoteLinkToIssue(request);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TeamFoundationApplicationCore.Log("Sample.SourceControl.Server.PlugIns.CodeCheckInEventHandler encountered an exception \n Exception:" + ex.ToString(), 123, System.Diagnostics.EventLogEntryType.Error);
            }
            return(EventNotificationStatus.ActionPermitted);
        }
예제 #12
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext,
                                                    NotificationType notificationType, object notificationEventArgs,
                                                    out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            statusMessage = string.Empty;
            properties    = null;

            if (notificationType == NotificationType.DecisionPoint)
            {
                try
                {
                    if (notificationEventArgs is CheckinNotification)
                    {
                        var  notification   = notificationEventArgs as CheckinNotification;
                        bool IsCheckInValid = true;
                        if (String.IsNullOrEmpty(notification.Comment))
                        {
                            statusMessage  = " Check in Comments Cannot Be empty";
                            IsCheckInValid = IsCheckInValid && false;
                        }
                        if (notification.NotificationInfo.WorkItemInfo.Length <= 0)
                        {
                            statusMessage  = "Associate Change set With a Work Item To Check In";
                            IsCheckInValid = IsCheckInValid && false;
                        }
                        if (!IsCheckInValid)
                        {
                            return(EventNotificationStatus.ActionDenied);
                        }
                    }
                }
                catch (Exception e)
                {
                    TeamFoundationApplicationCore.LogException("Check In Validation failed", e);
                }
            }
            return(EventNotificationStatus.ActionPermitted);
        }
        public async Task NotifyAsync(TeamFoundationRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string URL        = bot.GetSetting("spiraURL");
            string user       = bot.GetSetting("spiraUser");
            string password   = bot.GetSetting("spiraPassw");
            string projVers   = bot.GetSetting("spiraPvers");
            string projNumber = bot.GetSetting("spiraPnumber");
            int    status     = 0;
            int    projectId;

            Int32.TryParse(projNumber, out projectId);

            //Check that it is the correct kind of notification
            if (notification is BuildCompletionNotification)
            {
                BuildCompletionNotification buildCompletionNotification = (BuildCompletionNotification)notification;

                if (buildCompletionNotification.IsSuccessful)
                {
                    status = 2;  //sucess
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "Failed")
                {
                    status = 1; //failed
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "PartiallySucceeded")
                {
                    status = 3; //unstable
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "Stopped")
                {
                    status = 4; //aborted
                }
                else
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS:: The current build finished with a not supported" +
                                                      " status, please check TFS logs to see detailed information.", 0, EventLogEntryType.Warning);
                }


                DateTime date        = buildCompletionNotification.StartTime;
                String   sname       = buildCompletionNotification.ProjectName + " #" + buildCompletionNotification.BuildNumber;
                String   description = ("Information retrieved from TFS : Build requested by " +
                                        buildCompletionNotification.UserName + "<br/> from Team " +
                                        buildCompletionNotification.TeamNames + "<br/> and project collection " +
                                        buildCompletionNotification.TeamProjectCollection + "<br/> for " + sname +
                                        "<br/> with URL " + buildCompletionNotification.BuildUrl +
                                        "<br/> located at " + buildCompletionNotification.DropLocation +
                                        "<br/> Build Started at " + buildCompletionNotification.StartTime +
                                        "<br/> Build finished at " + buildCompletionNotification.FinishTime +
                                        "<br/> Status " + buildCompletionNotification.BuildStatus);
                //List<int> incidentIds;
                var    locationService = requestContext.GetService <TeamFoundationLocationService>();
                string baseUrl         = String.Format("{0}/", locationService.GetAccessMapping(requestContext,
                                                                                                "PublicAccessMapping").AccessPoint);
                TfsTeamProjectCollection tpc           = new TfsTeamProjectCollection(new Uri(baseUrl));
                VersionControlServer     sourceControl = tpc.GetService <VersionControlServer>();
                int revisionId = sourceControl.GetLatestChangesetId();

                //SPIRA CODE
                Uri uri = new Uri(URL + URL_SUFFIX);
                ImportExportClient spiraClient = SpiraClientFactory.CreateClient(uri);
                bool success = spiraClient.Connection_Authenticate2(user, password, "TFS Notifier for SpiraTeam v. 1.0.0");
                if (!success)
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: Unable to connect to the Spira server, please verify" +
                                                      " the provided information in the configuration file.", 0, EventLogEntryType.Error);
                }
                success = spiraClient.Connection_ConnectToProject(projectId);
                if (!success)
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: The project Id you specified either does not exist," +
                                                      "or your user does not have access to it! Please verify the configuration file.", 0, EventLogEntryType.Error);
                }

                RemoteRelease[] releases = spiraClient.Release_Retrieve(true);
                RemoteRelease   release  = releases.FirstOrDefault(r => r.VersionNumber == projVers);
                if (release != null)
                {
                    List <RemoteBuildSourceCode> revisions = new List <RemoteBuildSourceCode>();
                    RemoteBuildSourceCode        revision  = new RemoteBuildSourceCode();
                    revision.RevisionKey = revisionId.ToString();
                    revisions.Add(revision);

                    RemoteBuild newBuild = new RemoteBuild();
                    newBuild.Name          = sname;
                    newBuild.BuildStatusId = status;
                    newBuild.Description   = description;
                    newBuild.CreationDate  = date;
                    newBuild.Revisions     = revisions.ToArray();
                    newBuild.ReleaseId     = release.ReleaseId.Value;
                    spiraClient.Build_Create(newBuild);
                    await Task.Delay(10);
                }
                else
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: The release version number you specified does not " +
                                                      "exist in the current project! Please verify the configuration file.", 0, EventLogEntryType.Error);
                }
            }
        }