Example #1
0
        public int RunQuery(ILeanKitApi client, string[] parameters, TextWriter output, TextWriter errorOutput)
        {
            var boards = client.GetBoards();

            foreach (var board in boards)
            {
                if (parameters.Length > 0)
                {
                    bool found = true;
                    foreach (var parameter in parameters)
                    {
                        if (!board.Title.ToLower().Contains(parameter.ToLower()))
                        {
                            found = false;
                            break;
                        }
                    }
                    if (!found)
                    {
                        continue;
                    }
                }
                output.WriteLine(board.Id + " - " + board.Title);
            }

            return(0);
        }
Example #2
0
 public bool Initialize(string accountName, string emailAddress, string password)
 {
     try
     {
         var lkFactory = new LeanKitClientFactory();
         var lkAuth    = new LeanKitBasicAuth
         {
             Hostname = accountName,
             Username = emailAddress,
             Password = password
         };
         _api = lkFactory.Create(lkAuth);
         // Test authentication
         var boards = _api.GetBoards();
         if (boards == null)
         {
             return(false);
         }
         _cache.Set("boards", boards.ToArray(), DateTimeOffset.Now.AddMinutes(5));
         return(true);
     }
     catch (Exception)
     {
         _api = null;
         return(false);
     }
 }
		public LeanKitIntegration(long boardId, ILeanKitApi apiClient, IntegrationSettings settings)
		{
			_integrationSettings = settings;
			_boardId = boardId;
			_api = apiClient;
			ShouldContinue = true;
		}
Example #4
0
        public LeanKitCardViewHistory(ILeanKitApi api, long boardId, CardView card, int numberOfDays, DateTime date)
        {
            try
            {
                var unorderedHistory = api.GetCardHistory(boardId, card.Id);
                var orderedEvents    = unorderedHistory.OrderBy(c => c.ConvertedDateTime()).Reverse();
                history = orderedEvents.ToList();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("***** Error download history:\r\n" + ex.Message);
                history = new List <CardEvent>();
            }

            historyDate     = date.Date;
            historyPosition = 0;

            PointsPerDay = new List <CardPointsHistory>();

            cardLaneId = card.LaneId;
            cardSize   = card.Size != 0 ? card.Size : 1;

            PointsPerDay.Add(new CardPointsHistory(cardLaneId, cardSize));
            for (int i = 1; i < numberOfDays; i++)
            {
                historyDate = historyDate.AddDays(-1);
                ApplyHistory();
                PointsPerDay.Add(new CardPointsHistory(cardLaneId, cardSize));
            }
        }
 public LeanKitIntegration(long boardId, ILeanKitApi apiClient, IntegrationSettings settings)
 {
     _integrationSettings = settings;
     _boardId             = boardId;
     _api           = apiClient;
     ShouldContinue = true;
 }
        public int RunQuery(ILeanKitApi client, string[] parameters, TextWriter output, TextWriter errorOutput)
        {
            if (parameters.Length < 1)
            {
                errorOutput.WriteLine("No board ID specified");
                return(1);
            }
            if (!long.TryParse(parameters[0], out _boardId))
            {
                errorOutput.WriteLine("Invalid board ID specified");
                return(1);
            }

            int numberOfDaysHistory = 10;

            if (parameters.Length >= 2)
            {
                if (!int.TryParse(parameters[1], out numberOfDaysHistory))
                {
                    errorOutput.WriteLine("Invalid number of days specified");
                    return(1);
                }
            }

            _output     = output;
            _lanePoints = new LeanKit.Model.LaneHistory.LeanKitLanePointsHistory(client, _boardId);
            _lanePoints.Update(numberOfDaysHistory);

            OutputLanes(_lanePoints.Board.Backlog, 0);
            OutputLanes(_lanePoints.Board.Lanes, 0);
            OutputLanes(_lanePoints.Board.Archive, 0);

            return(0);
        }
            internal BoardSubscription(LeanKitAccountAuth auth, long boardId)
            {
                _boardId = boardId;
				LkClientApi = new LeanKitClientFactory().Create(auth);
				Integration = new LeanKitIntegrationFactory().Create(_boardId, auth);

                new Thread(WatchThread).Start();
            }
            internal BoardSubscription(LeanKitAccountAuth auth, long boardId)
            {
                _boardId    = boardId;
                LkClientApi = new LeanKitClientFactory().Create(auth);
                Integration = new LeanKitIntegrationFactory().Create(_boardId, auth);

                new Thread(WatchThread).Start();
            }
            internal BoardSubscription(ILeanKitAccountAuth auth, long boardId, int pollingFrequency)
            {
                _boardId = boardId;
				LkClientApi = new LeanKitClientFactory().Create(auth);
	            var settings = new IntegrationSettings {CheckForUpdatesIntervalSeconds = pollingFrequency};
	            Integration = new LeanKitIntegrationFactory().Create(_boardId, auth, settings);

                new Thread(WatchThread).Start();
            }
        public override ILeanKitApi CreateApi(string hostName, string userName, string password)
        {
            var api = _api;

            _api      = null;
            _hostName = hostName;
            _userName = userName;
            _password = password;
            return(api);
        }
            internal BoardSubscription(LeanKitAccountAuth auth, long boardId, int pollingFrequency)
            {
                _boardId    = boardId;
                LkClientApi = new LeanKitClientFactory().Create(auth);
                var settings = new IntegrationSettings {
                    CheckForUpdatesIntervalSeconds = pollingFrequency
                };

                Integration = new LeanKitIntegrationFactory().Create(_boardId, auth, settings);

                new Thread(WatchThread).Start();
            }
        protected override void OnCreateMockObjects()
        {
            MockBoardSubscriptionManager = new Mock <IBoardSubscriptionManager>();
            MockConfigurationProvider    = new Mock <IConfigurationProvider <Configuration> >();
            MockLocalStorage             = new Mock <ILocalStorage <AppSettings> >();
            MockLeanKitClientFactory     = new Mock <ILeanKitClientFactory>();
            MockLeanKitApi = new Mock <ILeanKitApi>();

            SubscriptionManager   = MockBoardSubscriptionManager.Object;
            ConfigurationProvider = MockConfigurationProvider.Object;
            LocalStorage          = MockLocalStorage.Object;
            LeanKitClientFactory  = MockLeanKitClientFactory.Object;
            LeanKitApi            = MockLeanKitApi.Object;
        }
        public int RunQuery(ILeanKitApi client, string[] parameters, TextWriter output, TextWriter errorOutput)
        {
            if (parameters.Length < 2)
            {
                errorOutput.WriteLine("No board ID and/or lane ID specified");
                return(1);
            }
            var cards = client.GetBoard(long.Parse(parameters[0])).GetLaneById(long.Parse(parameters[1])).Cards;

            foreach (var card in cards)
            {
                output.WriteLine(card.Title + "\t" + card.Description);
            }

            return(0);
        }
        public int RunQuery(ILeanKitApi client, string[] parameters, TextWriter output, TextWriter errorOutput)
        {
            if (parameters.Length < 1)
            {
                errorOutput.WriteLine("No board ID specified");
                return(1);
            }

            var backlog = client.GetBoard(long.Parse(parameters[0])).Backlog.ToArray();
            var lanes   = client.GetBoard(long.Parse(parameters[0])).Lanes.ToArray();
            var archive = client.GetBoard(long.Parse(parameters[0])).Archive.ToArray();

            OutputLanes(backlog, output, "", 0);
            OutputLanes(lanes, output, "", 0);
            OutputLanes(archive, output, "", 0);

            return(0);
        }
		public static long? CalculateLeanKitAssignedUserId(long boardId, Jira.Issue issue, ILeanKitApi leanKit) 
		{
			if (issue == null || issue.Fields == null || issue.Fields.Assignee == null 
				|| (	string.IsNullOrEmpty(issue.Fields.Assignee.Name)
					&&	string.IsNullOrEmpty(issue.Fields.Assignee.EmailAddress) 
					&&	string.IsNullOrEmpty(issue.Fields.Assignee.DisplayName)))
				return null;

			var lkUser = leanKit.GetBoard(boardId).BoardUsers.FirstOrDefault(x => x != null &&
				(((!string.IsNullOrEmpty(x.EmailAddress)) && (!string.IsNullOrEmpty(issue.Fields.Assignee.EmailAddress)) && x.EmailAddress.ToLowerInvariant() == issue.Fields.Assignee.EmailAddress.ToLowerInvariant()) ||
				((!string.IsNullOrEmpty(x.FullName)) && (!string.IsNullOrEmpty(issue.Fields.Assignee.Name)) && x.FullName.ToLowerInvariant() == issue.Fields.Assignee.Name.ToLowerInvariant()) ||
				((!string.IsNullOrEmpty(x.UserName)) && (!string.IsNullOrEmpty(issue.Fields.Assignee.Name)) && x.UserName.ToLowerInvariant() == issue.Fields.Assignee.Name.ToLowerInvariant()) ||
				((!string.IsNullOrEmpty(x.FullName)) && (!string.IsNullOrEmpty(issue.Fields.Assignee.DisplayName)) && x.FullName.ToLowerInvariant() == issue.Fields.Assignee.DisplayName.ToLowerInvariant())));
			if (lkUser != null)
				return lkUser.Id;

			return null;
		}
		public bool Initialize(string accountName, string emailAddress, string password)
		{
			try
			{
				var lkFactory = new LeanKitClientFactory();
				var lkAuth = new LeanKitBasicAuth
				{
					Hostname = accountName,
					Username = emailAddress,
					Password = password
				};
				_api = lkFactory.Create(lkAuth);
				// Test authentication
				var boards = _api.GetBoards();
				if (boards == null) return false;
				_cache.Set("boards", boards.ToArray(), DateTimeOffset.Now.AddMinutes(5));
				return true;
			}
			catch (Exception)
			{
				_api = null;
				return false;
			}
		}
		public static long? LeanKitAssignedUser(this GitHubPulls.Pull pull, long boardId, ILeanKitApi leanKit)
		{
			return CalculateLeanKitAssignedUserId(boardId, pull, leanKit);
		}
		public static long? CalculateLeanKitAssignedUserId(long boardId, GitHubIssues.Issue issue, ILeanKitApi leanKit) 
		{
			if (issue == null)
				return null;

			if (issue.Assignee != null && !string.IsNullOrEmpty(issue.Assignee.Login)) {
				var lkUser = leanKit.GetBoard(boardId).BoardUsers.FirstOrDefault(x => x != null &&
					(((!string.IsNullOrEmpty(x.EmailAddress)) && x.EmailAddress.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant()) ||
					((!string.IsNullOrEmpty(x.FullName)) && x.FullName.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant()) ||
					((!string.IsNullOrEmpty(x.UserName)) && x.UserName.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant())));
				if (lkUser != null)
					return lkUser.Id;
			}

			return null;
		}
        public static long?CalculateLeanKitAssignedUserId(long boardId, GitHubIssues.Issue issue, ILeanKitApi leanKit)
        {
            if (issue == null)
            {
                return(null);
            }

            if (issue.Assignee != null && !string.IsNullOrEmpty(issue.Assignee.Login))
            {
                var lkUser = leanKit.GetBoard(boardId).BoardUsers.FirstOrDefault(x => x != null &&
                                                                                 (((!string.IsNullOrEmpty(x.EmailAddress)) && x.EmailAddress.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant()) ||
                                                                                  ((!string.IsNullOrEmpty(x.FullName)) && x.FullName.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant()) ||
                                                                                  ((!string.IsNullOrEmpty(x.UserName)) && x.UserName.ToLowerInvariant() == issue.Assignee.Login.ToLowerInvariant())));
                if (lkUser != null)
                {
                    return(lkUser.Id);
                }
            }

            return(null);
        }
		public LeanKitIntegration(long boardId, ILeanKitApi apiClient) : this(boardId, apiClient, new IntegrationSettings())
		{
		}
		public static long? LeanKitAssignedUserId(this Jira.Issue issue, long boardId, ILeanKitApi leanKit)
		{
			return CalculateLeanKitAssignedUserId(boardId, issue, leanKit);
		}
		/// <summary>
		///     Factory method that creates and returns the <see cref="LeanKitIntegration" /> implementation using the
		///     LeanKitClient passed into the method.
		/// </summary>
		/// <remarks>
		///     This method should be used for consumers that would like to override the default
		///     <see cref="IRestCommandProcessor" />.
		/// </remarks>
		/// <param name="boardId">The Identity of the Board that will be watched and modified.</param>
		/// <param name="apiClient">The <see cref="ILeanKitApi" /> implementation used to communicate with the LeanKit API.</param>
		/// <returns></returns>
		public ILeanKitIntegration Create(long boardId, ILeanKitApi apiClient)
		{
			return new LeanKitIntegration(boardId, apiClient);
		}
Example #23
0
        protected virtual void BoardUpdate(long boardId, BoardChangedEventArgs eventArgs, ILeanKitApi integration)
        {
            if (eventArgs.BoardStructureChanged)
            {
                Log.Debug(String.Format("Received BoardStructureChanged event for [{0}], reloading Configuration", boardId));
                // TODO: Ideally this would be ReloadConfiguration(boardId);
                ReloadConfiguration();
            }

            var boardConfig = Configuration.Mappings.FirstOrDefault(x => x.Identity.LeanKit == boardId);

            if (boardConfig == null)
            {
                Log.Debug(String.Format("Expected a configuration for board [{0}].", boardId));
                return;
            }

            Log.Debug(String.Format("Received board changed event for board [{0}]", boardId));

            // check for content change events
            if (!boardConfig.UpdateTargetItems)
            {
                Log.Info("Skipped target item update because 'UpdateTargetItems' is disabled.");
            }
            else
            {
                Log.Info("Checking for updated cards.");
                if (eventArgs.UpdatedCards.Any())
                {
                    var itemsUpdated = new List <string>();
                    foreach (var updatedCardEvent in eventArgs.UpdatedCards)
                    {
                        try
                        {
                            if (updatedCardEvent.UpdatedCard == null)
                            {
                                throw new Exception("Updated card is null");
                            }
                            if (updatedCardEvent.OriginalCard == null)
                            {
                                throw new Exception("Original card is null");
                            }

                            var card = updatedCardEvent.UpdatedCard;

                            if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
                            {
                                // try to grab id from url
                                var pos = card.ExternalSystemUrl.LastIndexOf('=');
                                if (pos > 0)
                                {
                                    card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
                                }
                            }

                            if (string.IsNullOrEmpty(card.ExternalCardID))
                            {
                                continue;                                                                    // still invalid; skip this card
                            }
                            if (card.Title != updatedCardEvent.OriginalCard.Title)
                            {
                                itemsUpdated.Add("Title");
                            }
                            if (card.Description != updatedCardEvent.OriginalCard.Description)
                            {
                                itemsUpdated.Add("Description");
                            }
                            if (card.Tags != updatedCardEvent.OriginalCard.Tags)
                            {
                                itemsUpdated.Add("Tags");
                            }
                            if (card.Priority != updatedCardEvent.OriginalCard.Priority)
                            {
                                itemsUpdated.Add("Priority");
                            }
                            if (card.DueDate != updatedCardEvent.OriginalCard.DueDate)
                            {
                                itemsUpdated.Add("DueDate");
                            }
                            if (card.Size != updatedCardEvent.OriginalCard.Size)
                            {
                                itemsUpdated.Add("Size");
                            }
                            if (card.IsBlocked != updatedCardEvent.OriginalCard.IsBlocked)
                            {
                                itemsUpdated.Add("Blocked");
                            }

                            if (itemsUpdated.Count <= 0)
                            {
                                continue;
                            }

                            CardUpdated(card, itemsUpdated, boardConfig);
                        }
                        catch (Exception e)
                        {
                            var card = updatedCardEvent.UpdatedCard ?? updatedCardEvent.OriginalCard ?? new Card();
                            string.Format("Error processing blocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
                        }
                    }
                }
                if (eventArgs.BlockedCards.Any())
                {
                    var itemsUpdated = new List <string>();
                    foreach (var cardBlockedEvent in eventArgs.BlockedCards)
                    {
                        try
                        {
                            var card = cardBlockedEvent.BlockedCard;
                            if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
                            {
                                // try to grab id from url
                                var pos = card.ExternalSystemUrl.LastIndexOf('=');
                                if (pos > 0)
                                {
                                    card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
                                }
                            }

                            if (string.IsNullOrEmpty(card.ExternalCardID))
                            {
                                continue;                                                                        // still invalid; skip this card
                            }
                            if (card.IsBlocked != cardBlockedEvent.BlockedCard.IsBlocked)
                            {
                                itemsUpdated.Add("Blocked");
                            }

                            if (itemsUpdated.Count <= 0)
                            {
                                continue;
                            }
                            CardUpdated(card, itemsUpdated, boardConfig);
                        }
                        catch (Exception e)
                        {
                            var card = cardBlockedEvent.BlockedCard ?? new Card();
                            string.Format("Error processing blocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
                        }
                    }
                }
                if (eventArgs.UnBlockedCards.Any())
                {
                    var itemsUpdated = new List <string>();
                    foreach (var cardUnblockedEvent in eventArgs.UnBlockedCards)
                    {
                        try
                        {
                            var card = cardUnblockedEvent.UnBlockedCard;
                            if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
                            {
                                // try to grab id from url
                                var pos = card.ExternalSystemUrl.LastIndexOf('=');
                                if (pos > 0)
                                {
                                    card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
                                }
                            }

                            if (string.IsNullOrEmpty(card.ExternalCardID))
                            {
                                continue;                                                                        // still invalid; skip this card
                            }
                            if (card.IsBlocked != cardUnblockedEvent.UnBlockedCard.IsBlocked)
                            {
                                itemsUpdated.Add("Blocked");
                            }

                            if (itemsUpdated.Count <= 0)
                            {
                                continue;
                            }
                            CardUpdated(card, itemsUpdated, boardConfig);
                        }
                        catch (Exception e)
                        {
                            var card = cardUnblockedEvent.UnBlockedCard ?? new Card();
                            string.Format("Error processing unblocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
                        }
                    }
                }
            }


            // check for content change events
            if (!boardConfig.CreateTargetItems)
            {
                Log.Info("Skipped adding target items because 'AddTargetItems' is disabled.");
            }
            else
            {
                Log.Info("Checking for added cards.");
                if (eventArgs.AddedCards.Any())
                {
                    foreach (var newCard in eventArgs.AddedCards.Select(cardAddEvent => cardAddEvent.AddedCard)
                             .Where(newCard => newCard != null && string.IsNullOrEmpty(newCard.ExternalCardID)))
                    {
                        try
                        {
                            CreateNewItem(newCard, boardConfig);
                        }
                        catch (Exception e)
                        {
                            string.Format("Error processing newly created card, [{0}]: {1}", newCard.Id, e.Message).Error(e);
                        }
                    }
                }
            }

            //Ignore all other events except for MovedCardEvents
            if (!eventArgs.MovedCards.Any())
            {
                Log.Debug(String.Format("No Card Move Events detected event for board [{0}], exiting method", boardId));
                return;
            }

            UpdateBoardVersion(boardId);

            Log.Debug("Checking for cards moved to mapped lanes.");
            foreach (var movedCardEvent in eventArgs.MovedCards.Where(x => x != null && x.ToLane != null && x.MovedCard != null))
            {
                try
                {
                    if (!movedCardEvent.ToLane.Id.HasValue)
                    {
                        continue;
                    }

                    if (boardConfig.LaneToStatesMap.Any() &&
                        boardConfig.LaneToStatesMap.ContainsKey(movedCardEvent.ToLane.Id.Value))
                    {
                        var states = boardConfig.LaneToStatesMap[movedCardEvent.ToLane.Id.Value];
                        if (states != null && states.Count > 0)
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(movedCardEvent.MovedCard.ExternalCardID))
                                {
                                    UpdateStateOfExternalItem(movedCardEvent.MovedCard, states, boardConfig);
                                }
                                else if (boardConfig.CreateTargetItems)
                                {
                                    // This may be a task card being moved to the parent board, or card being moved from another board
                                    CreateNewItem(movedCardEvent.MovedCard, boardConfig);
                                }
                            }
                            catch (Exception e)
                            {
                                Log.Error("Exception for UpdateStateOfExternalItem: " + e.Message);
                            }
                        }
                        else
                        {
                            Log.Debug(String.Format("No states are mapped to the Lane [{0}]", movedCardEvent.ToLane.Id.Value));
                        }
                    }
                    else
                    {
                        Log.Debug(String.Format("No states are mapped to the Lane [{0}]", movedCardEvent.ToLane.Id.Value));
                    }
                }
                catch (Exception e)
                {
                    string.Format("Error processing moved card, [{0}]: {1}", movedCardEvent.MovedCard.Id, e.Message).Error(e);
                }
            }
        }
		public LeanKitIntegration(long boardId, ILeanKitApi apiClient)
		{
			_boardId = boardId;
			_api = apiClient;
			ShouldContinue = true;
		}
		protected override void OnCreateMockObjects()
		{
			MockBoardSubscriptionManager = new Mock<IBoardSubscriptionManager>();
			MockConfigurationProvider = new Mock<IConfigurationProvider<Configuration>>();
			MockLocalStorage = new Mock<ILocalStorage<AppSettings>>();
			MockLeanKitClientFactory = new Mock<ILeanKitClientFactory>();
			MockLeanKitApi = new Mock<ILeanKitApi>();

			SubscriptionManager = MockBoardSubscriptionManager.Object;
			ConfigurationProvider = MockConfigurationProvider.Object;
			LocalStorage = MockLocalStorage.Object;
			LeanKitClientFactory = MockLeanKitClientFactory.Object;
			LeanKitApi = MockLeanKitApi.Object;
		}
Example #26
0
 /// <summary>
 ///     Factory method that creates and returns the <see cref="LeanKitIntegration" /> implementation using the
 ///     LeanKitClient passed into the method.
 /// </summary>
 /// <remarks>
 ///     This method should be used for consumers that would like to override the default
 ///     <see cref="IRestCommandProcessor" />.
 /// </remarks>
 /// <param name="boardId">The Identity of the Board that will be watched and modified.</param>
 /// <param name="apiClient">The <see cref="ILeanKitApi" /> implementation used to communicate with the LeanKit API.</param>
 /// <returns></returns>
 public ILeanKitIntegration Create(long boardId, ILeanKitApi apiClient)
 {
     return(new LeanKitIntegration(boardId, apiClient));
 }
 public LeanKitTicker(string hostName, string userName, string password, long boardId, long laneId)
 {
     _api     = LeanKitFactory.Instance.CreateApi(hostName, userName, password);
     _boardId = boardId;
     _laneId  = laneId;
 }
 public LeanKitIntegration(long boardId, ILeanKitApi apiClient) : this(boardId, apiClient, new IntegrationSettings())
 {
 }
Example #29
0
 public LeanKitPoints(string hostName, string userName, string password)
 {
     _api = LeanKitFactory.Instance.CreateApi(hostName, userName, password);
 }
 public void SimulateUpdateEvent(long boardId, BoardChangedEventArgs eventArgs, ILeanKitApi api)
 {
     base.BoardUpdate(boardId, eventArgs, api);
 }
 public LeanKitIntegration(long boardId, ILeanKitApi apiClient)
 {
     _boardId       = boardId;
     _api           = apiClient;
     ShouldContinue = true;
 }
		public void Setup()
		{
			_apiMock = MockRepository.GenerateMock<ILeanKitApi>();
		}
Example #33
0
 public static long?LeanKitAssignedUserId(this Jira.Issue issue, long boardId, ILeanKitApi leanKit)
 {
     return(CalculateLeanKitAssignedUserId(boardId, issue, leanKit));
 }
		protected virtual void BoardUpdate(long boardId, BoardChangedEventArgs eventArgs, ILeanKitApi integration)
		{
		    if (eventArgs.BoardStructureChanged)
		    {
		        Log.Debug(String.Format("Received BoardStructureChanged event for [{0}], reloading Configuration", boardId));
		        // TODO: Ideally this would be ReloadConfiguration(boardId);
		        ReloadConfiguration();
		    }

		    var boardConfig = Configuration.Mappings.FirstOrDefault(x => x.Identity.LeanKit == boardId);
		    if (boardConfig == null)
		    {
		        Log.Debug(String.Format("Expected a configuration for board [{0}].", boardId));
		        return;
		    }

		    Log.Debug(String.Format("Received board changed event for board [{0}]", boardId));

            // check for content change events
		    if (!boardConfig.UpdateTargetItems)
		    {
		        Log.Info("Skipped target item update because 'UpdateTargetItems' is disabled.");
		    }
		    else
		    {
		        Log.Info("Checking for updated cards.");
			    if (eventArgs.UpdatedCards.Any())
			    {
				    var itemsUpdated = new List<string>();
				    foreach (var updatedCardEvent in eventArgs.UpdatedCards)
				    {
					    try
					    {
						    if (updatedCardEvent.UpdatedCard == null) throw new Exception("Updated card is null");
						    if (updatedCardEvent.OriginalCard == null) throw new Exception("Original card is null");

						    var card = updatedCardEvent.UpdatedCard;

						    if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
						    {
							    // try to grab id from url
							    var pos = card.ExternalSystemUrl.LastIndexOf('=');
							    if (pos > 0)
								    card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
						    }

						    if (string.IsNullOrEmpty(card.ExternalCardID)) continue; // still invalid; skip this card

						    if (card.Title != updatedCardEvent.OriginalCard.Title)
							    itemsUpdated.Add("Title");
						    if (card.Description != updatedCardEvent.OriginalCard.Description)
							    itemsUpdated.Add("Description");
						    if (card.Tags != updatedCardEvent.OriginalCard.Tags)
							    itemsUpdated.Add("Tags");
						    if (card.Priority != updatedCardEvent.OriginalCard.Priority)
							    itemsUpdated.Add("Priority");
						    if (card.DueDate != updatedCardEvent.OriginalCard.DueDate)
							    itemsUpdated.Add("DueDate");
						    if (card.Size != updatedCardEvent.OriginalCard.Size)
							    itemsUpdated.Add("Size");
						    if (card.IsBlocked != updatedCardEvent.OriginalCard.IsBlocked)
							    itemsUpdated.Add("Blocked");

						    if (itemsUpdated.Count <= 0) continue;

						    CardUpdated(card, itemsUpdated, boardConfig);
					    }
					    catch (Exception e)
					    {
							var card = updatedCardEvent.UpdatedCard ?? updatedCardEvent.OriginalCard ?? new Card();
							string.Format("Error processing blocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
					    }
				    }
			    }
			    if (eventArgs.BlockedCards.Any())
				{
		            var itemsUpdated = new List<string>();
					foreach (var cardBlockedEvent in eventArgs.BlockedCards)
					{
						try
						{
							var card = cardBlockedEvent.BlockedCard;
							if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
							{
								// try to grab id from url
								var pos = card.ExternalSystemUrl.LastIndexOf('=');
								if (pos > 0)
									card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
							}

							if (string.IsNullOrEmpty(card.ExternalCardID)) continue; // still invalid; skip this card

							if (card.IsBlocked != cardBlockedEvent.BlockedCard.IsBlocked)
								itemsUpdated.Add("Blocked");

							if (itemsUpdated.Count <= 0) continue;
							CardUpdated(card, itemsUpdated, boardConfig);
						}
						catch (Exception e)
						{
							var card = cardBlockedEvent.BlockedCard ?? new Card();
							string.Format("Error processing blocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
						}
					}
				}
				if (eventArgs.UnBlockedCards.Any())
				{
					var itemsUpdated = new List<string>();
					foreach (var cardUnblockedEvent in eventArgs.UnBlockedCards) 
					{
						try
						{
							var card = cardUnblockedEvent.UnBlockedCard;
							if (string.IsNullOrEmpty(card.ExternalCardID) && !string.IsNullOrEmpty(card.ExternalSystemUrl))
							{
								// try to grab id from url
								var pos = card.ExternalSystemUrl.LastIndexOf('=');
								if (pos > 0)
									card.ExternalCardID = card.ExternalSystemUrl.Substring(pos + 1);
							}

							if (string.IsNullOrEmpty(card.ExternalCardID)) continue; // still invalid; skip this card

							if (card.IsBlocked != cardUnblockedEvent.UnBlockedCard.IsBlocked)
								itemsUpdated.Add("Blocked");

							if (itemsUpdated.Count <= 0) continue;
							CardUpdated(card, itemsUpdated, boardConfig);
						}
						catch (Exception e)
						{
							var card = cardUnblockedEvent.UnBlockedCard ?? new Card();
							string.Format("Error processing unblocked card, [{0}]: {1}", card.Id, e.Message).Error(e);
						}
					}					
				}
		    }


            // check for content change events
			if (!boardConfig.CreateTargetItems)
			{
				Log.Info("Skipped checking for newly added cards because 'CreateTargetItems' is disabled.");
			}
			else
			{
				Log.Info("Checking for added cards.");
				if (eventArgs.AddedCards.Any())
				{
					foreach (var newCard in eventArgs.AddedCards.Select(cardAddEvent => cardAddEvent.AddedCard)
						.Where(newCard => newCard != null && string.IsNullOrEmpty(newCard.ExternalCardID)))
					{
						try
						{
							CreateNewItem(newCard, boardConfig);
						}
						catch (Exception e)
						{
							string.Format("Error processing newly created card, [{0}]: {1}", newCard.Id, e.Message).Error(e);
						}
					}
				}
			}

			if (!boardConfig.UpdateTargetItems && !boardConfig.CreateTargetItems)
			{
				Log.Info("Skipped checking moved cards because 'UpdateTargetItems' and 'CreateTargetItems' are disabled.");
				UpdateBoardVersion(boardId);
				return;
			}

			if (eventArgs.MovedCards.Any())
			{
				Log.Debug("Checking for cards moved to mapped lanes.");
				foreach (var movedCardEvent in eventArgs.MovedCards.Where(x => x != null && x.ToLane != null && x.MovedCard != null))
				{
					try
					{
						if (!movedCardEvent.ToLane.Id.HasValue) continue;

						if (boardConfig.LaneToStatesMap.Any() &&
							boardConfig.LaneToStatesMap.ContainsKey(movedCardEvent.ToLane.Id.Value))
						{
							var states = boardConfig.LaneToStatesMap[movedCardEvent.ToLane.Id.Value];
							if (states != null && states.Count > 0)
							{
								try
								{
									if (!string.IsNullOrEmpty(movedCardEvent.MovedCard.ExternalCardID) && boardConfig.UpdateTargetItems)
									{
										UpdateStateOfExternalItem(movedCardEvent.MovedCard, states, boardConfig);
									}
									else if (string.IsNullOrEmpty(movedCardEvent.MovedCard.ExternalCardID) && boardConfig.CreateTargetItems)
									{
										// This may be a task card being moved to the parent board, or card being moved from another board
										CreateNewItem(movedCardEvent.MovedCard, boardConfig);
									}
								}
								catch (Exception e)
								{
									Log.Error("Exception for UpdateStateOfExternalItem: " + e.Message);
								}
							}
							else
								Log.Debug(string.Format("No states are mapped to the Lane [{0}]", movedCardEvent.ToLane.Id.Value));
						}
						else
						{
							Log.Debug(string.Format("No states are mapped to the Lane [{0}]", movedCardEvent.ToLane.Id.Value));
						}
					}
					catch (Exception e)
					{
						string.Format("Error processing moved card, [{0}]: {1}", movedCardEvent.MovedCard.Id, e.Message).Error(e);
					}
				}
			}
			else
			{
				Log.Debug(string.Format("No Card Move Events detected event for board [{0}], exiting method", boardId));
			}

			UpdateBoardVersion(boardId);

		}
Example #35
0
        public static long?CalculateLeanKitAssignedUserId(long boardId, Jira.Issue issue, ILeanKitApi leanKit)
        {
            if (issue == null || issue.Fields == null || issue.Fields.Assignee == null ||
                (string.IsNullOrEmpty(issue.Fields.Assignee.Name) &&
                 string.IsNullOrEmpty(issue.Fields.Assignee.EmailAddress) &&
                 string.IsNullOrEmpty(issue.Fields.Assignee.DisplayName)))
            {
                return(null);
            }

            var lkUser = leanKit.GetBoard(boardId).BoardUsers.FirstOrDefault(x => x != null &&
                                                                             (((!string.IsNullOrEmpty(x.EmailAddress)) &&
                                                                               (!string.IsNullOrEmpty(
                                                                                    issue.Fields.Assignee.EmailAddress)) &&
                                                                               x.EmailAddress.ToLowerInvariant() ==
                                                                               issue.Fields.Assignee.EmailAddress
                                                                               .ToLowerInvariant()) ||
                                                                              ((!string.IsNullOrEmpty(x.FullName)) &&
                                                                               (!string.IsNullOrEmpty(
                                                                                    issue.Fields.Assignee.Name)) &&
                                                                               x.FullName.ToLowerInvariant() ==
                                                                               issue.Fields.Assignee.Name.ToLowerInvariant()) ||
                                                                              ((!string.IsNullOrEmpty(x.UserName)) &&
                                                                               (!string.IsNullOrEmpty(
                                                                                    issue.Fields.Assignee.Name)) &&
                                                                               x.UserName.ToLowerInvariant() ==
                                                                               issue.Fields.Assignee.Name.ToLowerInvariant()) ||
                                                                              ((!string.IsNullOrEmpty(x.FullName)) &&
                                                                               (!string.IsNullOrEmpty(
                                                                                    issue.Fields.Assignee.DisplayName)) &&
                                                                               x.FullName.ToLowerInvariant() ==
                                                                               issue.Fields.Assignee.DisplayName
                                                                               .ToLowerInvariant())));

            if (lkUser != null)
            {
                return(lkUser.Id);
            }

            return(null);
        }
Example #36
0
 public LeanKitLanePointsHistory(ILeanKitApi api, long boardId)
 {
     _api     = api;
     _boardId = boardId;
 }
Example #37
0
 public LeanKitLanePointsHistory(string hostName, string userName, string password, long boardId)
 {
     _api     = LeanKitFactory.Instance.CreateApi(hostName, userName, password);
     _boardId = boardId;
 }
		public void SimulateUpdateEvent(long boardId, BoardChangedEventArgs eventArgs, ILeanKitApi api)
		{
			base.BoardUpdate(boardId, eventArgs, api);
		}
 public static long?LeanKitAssignedUser(this GitHubPulls.Pull pull, long boardId, ILeanKitApi leanKit)
 {
     return(CalculateLeanKitAssignedUserId(boardId, pull, leanKit));
 }