/// <summary> /// Compares the selected changeset with previous version /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void compareWithPreviousVersionToolStripMenuItem_Click(object sender, EventArgs e) { try { // Index in result int firstIndex = this.listViewSearchResults.SelectedIndices[0]; //Index in actual history firstIndex = _currentHistory.IndexOf(this._currentResult[firstIndex]); int secondIndex = firstIndex + 1; if (secondIndex < _currentHistory.Count) { string sourceChangesetId = this._currentHistory[firstIndex].ChangesetId.ToString(); string targetChangesetId = this._currentHistory[secondIndex].ChangesetId.ToString(); //srcPath and targetPath will be different in case of renamed else same string srcPath = this._currentHistory[firstIndex].Changes_0_ServerItem; string targetPath = this._currentHistory[secondIndex].Changes_0_ServerItem; TfsHelper.Compare(sourceChangesetId, targetChangesetId, _serverUri, srcPath, targetPath); } else { MessageBox.Show("No previous version available.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Throws an error if Entity is null and it's using a real CRM database /// -or- /// Throws an error if the CRM database is a local CRM database, and there are no serialized version of the files /// to deserialize /// </summary> /// <param name="service"></param> /// <param name="entity"></param> private Entity VerifyAssumption(IOrganizationService service, Entity entity) { if (entity == null) { var mock = service as FakeIOrganizationService; // If the service is a Mock, get the Actual Service to determine if it is local or not... if ( (mock != null && !(mock.ActualService is LocalCrmDatabaseOrganizationService)) || (mock == null && !(service is LocalCrmDatabaseOrganizationService)) || FileIsNullOrEmpty(GetSerializedFilePath(AssumptionsNamespaceRelativePath))) { throw new Exception(string.Format("Assumption {0} made an ass out of you and me. The entity assumed to be there, was not found.", AssumptionsNamespaceRelativePath)); } entity = GetTestEntityFromXml(AssumptionsNamespaceRelativePath); var localService = mock == null ? (LocalCrmDatabaseOrganizationService)service : (LocalCrmDatabaseOrganizationService)mock.ActualService; var isSelfReferencing = CreateForeignReferences(localService, entity); if (isSelfReferencing) { service.Update(entity); } else { entity.Id = service.Create(entity); } } else if (Debugger.IsAttached) { TfsHelper.CheckoutAndUpdateFileIfDifferent(GetSerializedFilePath(AssumptionsNamespaceRelativePath), entity.Serialize(true)); } return(entity); }
/// <summary> /// Obtains dependencies (predecessors/succcesors) for the given PBI, and raises an event informing about this. /// </summary> /// <param name="pbiId">Product Backlog Item Id</param> public void ImportDependenciesFromTfs(int pbiId) { try { this.RaiseDependenciesModelAboutToChange(); byte successorsDepth = 3; byte predecessorsDepth = 3; var workItem = this.WorkItemStore.GetWorkItem(pbiId); var theModel = new Dictionary <int, DependencyItem>(); DependencyItem mainDependencyItem = new DependencyItem(pbiId) { Title = workItem.Title, State = workItem.State, Comment = Path.GetFileName(workItem.IterationPath) }; mainDependencyItem.Tags.AddRange(TfsHelper.GetTags(workItem)); theModel.Add(pbiId, mainDependencyItem); this.GetPredecessorsRec(theModel, workItem, predecessorsDepth); this.GetSuccessorsRec(theModel, workItem, successorsDepth); this.DependenciesModel = theModel; this.RaiseDependenciesModelChanged(); } catch (Exception ex) { this.Logger.Error(string.Format(@"{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace)); this.RaiseDependenciesModelCouldNotBeChanged(); throw; } }
private void WriteTfsInformation(TextWriter writer, ICollection <SolutionProject> projects) { if (!_solution.IsSccBound) { return; } Uri tfsName = _settings.TfsName; string tfsFolder; if (!TfsHelper.TryGetTeamProjectCollection(_solution.RootPath, ref tfsName, out tfsFolder)) { return; } _settings.TfsName = tfsName; writer.WriteLine("\tGlobalSection({0}) = preSolution", "TeamFoundationVersionControl"); writer.WriteLine("\t\tSccNumberOfProjects = {0}", projects.Count); writer.WriteLine("\t\tSccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}"); writer.WriteLine("\t\tSccTeamFoundationServer = " + tfsName); var n = 0; foreach (var project in projects) { WriteTeamFoundationProject(writer, n, project, tfsFolder, tfsName.ToString()); ++n; } writer.WriteLine("\tEndGlobalSection"); }
public TfsHistorySearchWinForm(TfsHelper tfsHelper) { InitializeComponent(); //Get the server Uri and server path of the selected item tfsHelper.GetServerUriAndItemPath(out this._serverUri, out this._itemPath, out _isFolder); textBoxServerName.Text = this._serverUri; textBoxFilePath.Text = this._itemPath; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { CodestrikerToolWindowCommand.Initialize(this); base.Initialize(); TfsHelper tfsHelper = TfsHelper.Instance; tfsHelper.ContextChanged += TfsHelper_ContextChanged; tfsHelper.UsernameChanged += TfsHelper_UsernameChanged; tfsHelper.ConnectToFirstServerInList(); }
//Constructor public CodestrikerPluginViewModel() { TransportObject = new DiffTransportObject(); m_TfsHelper = TfsHelper.Instance; m_TfsHelper.UsernameChanged += M_TfsHelper_UsernameChanged; m_TfsHelper.ContextChanged += ProjectsChanged; m_IsCreateTopicPending = false; m_ErrorBoxVisibility = Visibility.Collapsed; CreateCommands(); }
public void ShouldDoNothingBecauseRemoteAlreadyExisting() { const string GIT_BRANCH_TO_INIT = "myBranch"; InitMocks4Tests(GIT_BRANCH_TO_INIT, out var gitRepository, out var trunkGitTfsRemoteMock, out var newBranchRemoteMock, out var tfsHelperMock); trunkGitTfsRemoteMock.Name = nameof(trunkGitTfsRemoteMock); trunkGitTfsRemoteMock.Setup(r => r.Fetch(It.IsAny <bool>(), It.IsAny <int>(), It.IsAny <IRenameResult>())).Returns(new GitTfsRemote.FetchResult() { IsSuccess = true }); trunkGitTfsRemoteMock.Setup(t => t.InitBranch(It.IsAny <RemoteOptions>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <IRenameResult>())).Returns(newBranchRemoteMock.Object); tfsHelperMock.Setup(t => t.GetRootChangesetForBranch("$/MyProject/MyBranch", -1, null)).Returns(new List <RootBranch>() { new RootBranch(2010, "$/MyProject/MyBranch") }); TfsHelper tfsHelper = new TfsHelper(mocks.Container, null); Mock <IGitTfsRemote> gitTfsRemoteMock = new Mock <IGitTfsRemote>().SetupAllProperties(); gitTfsRemoteMock.SetupGet(x => x.Tfs).Returns(tfsHelper); IGitTfsRemote existingBranchRemote = gitTfsRemoteMock.Object; existingBranchRemote.TfsUsername = "******"; existingBranchRemote.TfsPassword = "******"; gitTfsRemoteMock.SetupGet(x => x.TfsRepositoryPath).Returns("$/MyProject/MyBranch"); gitTfsRemoteMock.SetupGet(x => x.TfsUrl).Returns("http://myTfsServer:8080/tfs"); gitRepository.Name = nameof(gitRepository); gitRepository.Setup(x => x.ReadTfsRemote("default")).Returns(trunkGitTfsRemoteMock.Object).Verifiable(); gitRepository.Setup(x => x.ReadAllTfsRemotes()).Returns(new List <IGitTfsRemote> { trunkGitTfsRemoteMock.Object, existingBranchRemote }).Verifiable(); newBranchRemoteMock.Setup(r => r.Fetch(It.IsAny <bool>(), It.IsAny <int>(), It.IsAny <IRenameResult>())) .Returns(new GitTfsRemote.FetchResult() { IsSuccess = true }).Verifiable(); Assert.Equal(GitTfsExitCodes.OK, mocks.ClassUnderTest.Run("$/MyProject/MyBranch", GIT_BRANCH_TO_INIT)); gitRepository.Verify(x => x.AssertValidBranchName(GIT_BRANCH_TO_INIT), Times.Never); gitRepository.Verify(); trunkGitTfsRemoteMock.Verify(); newBranchRemoteMock.Verify(); }
public static string GetBranchNameOrEmpty(Solution solution) { //dynamic vce = Globals.DTE.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt"); //if (vce != null && vce.SolutionWorkspace != null) { // return vce.SolutionWorkspace.Name; //} var sn = solution?.FullName; if (string.IsNullOrEmpty(sn)) { return(string.Empty); } var name = string.Empty; //Globals.InvokeOnUIThread(() => name = TfsHelper.GetBranchNameFromLocalFile(Path.GetDirectoryName(sn))); //Causes slowness due to UI thread. name = TfsHelper.GetBranchNameFromLocalFile(Path.GetDirectoryName(sn)); return(name ?? string.Empty); }
/// <summary> /// Compares the selected changesets /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void compareToolStripMenuItem_Click(object sender, EventArgs e) { try { int firstIndex = this.listViewSearchResults.SelectedIndices[0]; int secondIndex = this.listViewSearchResults.SelectedIndices[1]; string sourceChangesetId = this._currentResult[firstIndex].ChangesetId.ToString(); string targetChangesetId = this._currentResult[secondIndex].ChangesetId.ToString(); //srcPath and targetPath will be different in case of renamed else same string srcPath = this._currentResult[firstIndex].Changes_0_ServerItem; string targetPath = this._currentResult[secondIndex].Changes_0_ServerItem; TfsHelper.Compare(sourceChangesetId, targetChangesetId, _serverUri, srcPath, targetPath); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public ActionResult NewRequest(Request newRequest, string message, HttpPostedFileBase newFile) { var r = Repository.FindRequest(1005); SendNewRequestMail(r); newRequest.DateCreated = DateTime.Now; newRequest.BrandId = ViewBag.BrandId; newRequest.UserId = ViewBag.UserId; newRequest.Status = "New"; RequestMessage reqMessage = new RequestMessage(); reqMessage.DateCreated = DateTime.Now; reqMessage.Message = message; reqMessage.UserId = ViewBag.UserId; if (newFile != null && newFile.ContentLength > 0) { byte[] file = new byte[newFile.InputStream.Length]; newFile.InputStream.Read(file, 0, file.Length); reqMessage.AttachmentFilename = newFile.FileName; reqMessage.AttachmentData = file; } newRequest.RequestMessages.Add(reqMessage); var requestId = Repository.SaveRequest(newRequest); var tfsId = TfsHelper.CreateTask(newRequest.Title, reqMessage.Message, newRequest.RequestType, null, requestId.ToString(), newRequest.Priority.GetPriority()); if (!string.IsNullOrEmpty(tfsId)) { newRequest.TfsId = int.Parse(tfsId); Repository.UpdateRequest(newRequest); } SendNewRequestMail(newRequest); return(View("RequestSaved", requestId)); }
private void GetPredecessorsRec(Dictionary <int, DependencyItem> model, WorkItem parent, byte level) { if (level == 0) { return; } level--; DependencyItem innerDependencyItem; var predecessors = this.GetPredecessorsFromTfs(parent); foreach (var predecessor in predecessors) { innerDependencyItem = new DependencyItem(predecessor.Id) { Title = predecessor.Title, State = predecessor.State, Comment = Path.GetFileName(predecessor.IterationPath) }; innerDependencyItem.Tags.AddRange(TfsHelper.GetTags(predecessor)); try { if (!model.ContainsKey(predecessor.Id)) { model.Add(predecessor.Id, innerDependencyItem); } if (!model[predecessor.Id].Successors.Contains(parent.Id)) { model[predecessor.Id].Successors.Add(parent.Id); } } catch (Exception) { throw; } this.GetPredecessorsRec(model, predecessor, level); } }
/// <summary> /// Searches the item history for the specified keywords /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonSearch_Click(object sender, EventArgs e) { buttonSearch.Enabled = false; toolStripStatusLabel.Text = "Searching..."; this.listViewSearchResults.Items.Clear(); this._currentResult.Clear(); Cursor.Current = Cursors.WaitCursor; _serverUri = textBoxServerName.Text; _itemPath = textBoxFilePath.Text; try { // Get all history of specified item this._currentHistory = TfsHelper.GetHistory(_serverUri, _itemPath); if (_currentHistory.Count > 0) { string[] searchWords = Regex.Split(textBoxSearch.Text, "\\s* |,"); _currentResult = SearchHistory(this._currentHistory, searchWords); if (_currentResult.Count > 0) { PopulateListView(listViewSearchResults, _currentResult); } toolStripStatusLabel.Text = _currentResult.Count.ToString() + " results found"; } else { toolStripStatusLabel.Text = "0 results found"; } } catch (Exception ex) { toolStripStatusLabel.Text = string.Empty; MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } Cursor.Current = Cursors.Default; buttonSearch.Enabled = true; }
public static void GenerateMocks(string serviceUtilsProjFileName, IEnumerable <Type> types, Type nullableAttributeType) { string logServicePath = Path.GetDirectoryName(serviceUtilsProjFileName); var filesServices = new List <TfsHelper.FileInfo>(); var filesLoggedServices = new List <TfsHelper.FileInfo>(); foreach (var type in types) { foreach (var f in GenerateLogServiceFile(logServicePath, type, nullableAttributeType)) { filesLoggedServices.Add(new TfsHelper.FileInfo(f)); } if (type.Name != "IService") { filesServices.Add(new TfsHelper.FileInfo(type.Name + ".cs")); filesServices.Add(new TfsHelper.FileInfo(type.Name.Substring(1) + ".cs")); } } TfsHelper.EnsureReferencesInProjectFile(serviceUtilsProjFileName, filesLoggedServices, "", null); }
private void PopulateDependenciesWithFlatQuery(Dictionary <int, DependencyItem> dependenciesModel, Query query, QueryDefinition queryDef) { byte successorsDepth = 3; byte predecessorsDepth = 3; int pbis = 0; var queryResults = query.RunQuery(); foreach (WorkItem workItem in queryResults) { if (workItem.Type.Name != "Product Backlog Item") { continue; } pbis++; if (!dependenciesModel.ContainsKey(workItem.Id)) { DependencyItem mainDependencyItem = new DependencyItem(workItem.Id) { Title = workItem.Title, State = workItem.State, Comment = Path.GetFileName(workItem.IterationPath) }; mainDependencyItem.Tags.AddRange(TfsHelper.GetTags(workItem)); dependenciesModel.Add(workItem.Id, mainDependencyItem); } // Todo: optimize this rec's, these used to be inside the if above this.GetPredecessorsRec(dependenciesModel, workItem, predecessorsDepth); this.GetSuccessorsRec(dependenciesModel, workItem, successorsDepth); } if (pbis == 0) { throw new Exception(string.Format("[TFS] The query '{0}' does not have any PBI's", queryDef.Name)); } }
/// <summary> /// Rules: /// 1. Take the only not Done item /// 2. Only 1 task should be there /// 3. Take user from this Task /// 4. Otherwise assign to Default Test User /// </summary> private string FindUserToTestFromLinkedItems(JObject parentWorkItem) { var relations = parentWorkItem["relations"]; if (relations == null) { _logger.Log(LogLevel.Info, $"This workitem doen't have any linked issues, so can't find user to reassign."); return(null); } _logger.Log(LogLevel.Info, "Finding test user in related workitems..."); var assignedList = new List <string>(); foreach (var relation in (JArray)relations) { var relationType = relation["rel"].ToString(); if (relationType == "System.LinkTypes.Hierarchy-Forward") { var workItemUrl = relation["url"].ToString(); var workItem = _tfsCrudManager.GetWorkItem(workItemUrl); if (workItem != null) { var fields = workItem["fields"]; var type = fields["System.WorkItemType"].ToString(); if (type != "Task") { _logger.Debug($"Skipping non-task items ({type})"); continue; } var assignedTo = fields["System.AssignedTo"]; if (assignedTo == null) { _logger.Debug($"Skipping Unassigned users"); continue; } var assignedToStr = assignedTo.ToString(); var assignedToFriendlyName = TfsHelper.GetUserNameFromString(assignedToStr, false); Func <string> itemDescriptionFunc = () => { return($"{assignedToFriendlyName} | {fields["System.Title"]}"); }; var state = fields["System.State"].ToString(); if (state == Constants.Tfs.State.Done.GetDescription()) { _logger.Debug($"Skipping Done items [{itemDescriptionFunc()}]"); continue; } if (state == Constants.Tfs.State.Removed.GetDescription()) { _logger.Debug($"Skipping Removed items [{itemDescriptionFunc()}]"); continue; } var assignedToDomainUser = TfsHelper.GetUserNameFromString(assignedToStr); if (assignedToDomainUser != null) { _logger.Debug($"Added user to temporary matches [{itemDescriptionFunc()}]"); assignedList.Add(assignedToStr); } var activityType = fields["Microsoft.VSTS.Common.Activity"]; if (activityType != null) { if (activityType.ToString() == Constants.Tfs.ActivityNames.DevelopmentActivityName) { throw new DeveloperHasNotFinishedTaskException(assignedToDomainUser); } } } } } if (assignedList.Count == 1) { var singleUser = assignedList.First(); _logger.Info($"Found {singleUser} user, probably that's tester..."); return(singleUser); } if (assignedList.Count > 1) { _logger.Info($"We've found {assignedList.Count} users. Can't decide which one to take :)"); } _logger.Log(LogLevel.Info, "User is not found at all."); return(null); }
public IEnumerable <Node <WorkItemNode> > PullData(DateTime startDateTime, DateTime endDateTime) { var wi = m_data.PullData(startDateTime, endDateTime); return(TfsHelper.BuildWorkItemGraph(wi)); }
private void worker_DoWork(object sender, DoWorkEventArgs e) { // run all background tasks here data = TfsHelper.SetPathParams(((dynamic)(e.Argument)).ProjPath, ((dynamic)(e.Argument)).TfsPath); }
private void generateDefinitionsToolStripMenuItem_Click(object sender, EventArgs e) { var fileList = new List <TfsHelper.FileInfo>(); foreach (var item in this.entityCollection.SelectedDefinitions) { var sb = new StringBuilder(); sb.AppendLine("using Model.Sdk;"); sb.AppendLine("using System;"); sb.AppendLine("using System.CodeDom.Compiler;"); sb.AppendLine("using System.ComponentModel.DataAnnotations;"); sb.AppendLine("using System.Diagnostics.CodeAnalysis;"); sb.AppendLine(); sb.AppendLine("namespace Model"); sb.AppendLine("{"); sb.AppendLine("\t[GeneratedCode(\"XrmFramework\", \"1.0\")]"); sb.AppendLine("\t[EntityDefinition]\r\n"); sb.AppendLine("\t[ExcludeFromCodeCoverage]\r\n"); sb.AppendFormat("\tpublic static class {0}\r\n", item.Name); sb.AppendLine("\t{"); sb.AppendFormat("\t\tpublic const string EntityName = \"{0}\";\r\n", item.LogicalName); sb.AppendFormat("\t\tpublic const string EntityCollectionName = \"{0}\";\r\n", item.LogicalCollectionName); foreach (var t in item.AdditionalInfoCollection.Definitions) { sb.AppendLine(); sb.AppendFormat("\t\tpublic const {0} {1} = {2};\r\n", t.Type, t.Name, t.Type == "String" ? "\"" + (string)t.Value + "\"" : t.Value); } sb.AppendLine(); sb.AppendLine("\t\t[SuppressMessage(\"Microsoft.Design\", \"CA1034:NestedTypesShouldNotBeVisible\")]"); sb.AppendLine("\t\tpublic static class Columns"); sb.AppendLine("\t\t{"); foreach (var attr in item.AttributesCollection.SelectedDefinitions) { sb.Append(attr.Summary); if (!string.IsNullOrEmpty(attr.Type)) { sb.AppendFormat("\t\t\t[AttributeMetadata(AttributeTypeCode.{0})]\r\n", attr.Type); } if (attr.Enum != null) { sb.AppendFormat("\t\t\t[OptionSet(typeof({0}))]\r\n", attr.Enum.Name); } if (attr.IsPrimaryIdAttribute) { sb.AppendLine("\t\t\t[PrimaryAttribute(PrimaryAttributeType.Id)]"); } if (attr.IsPrimaryNameAttribute) { sb.AppendLine("\t\t\t[PrimaryAttribute(PrimaryAttributeType.Name)]"); } if (attr.IsPrimaryImageAttribute) { sb.AppendLine("\t\t\t[PrimaryAttribute(PrimaryAttributeType.Image)]"); } if (attr.StringMaxLength.HasValue) { sb.AppendLine($"\t\t\t[StringLength({attr.StringMaxLength.Value})]"); } if (attr.MinRange.HasValue && attr.MaxRange.HasValue) { sb.AppendLine($"\t\t\t[Range({attr.MinRange.Value}, {attr.MaxRange.Value})]"); } foreach (var keyName in attr.KeyNames) { sb.AppendFormat("\t\t\t[Key(AlternateKeyNames.{0})]\r\n", keyName); } if (attr.DateTimeBehavior != null) { var behavior = string.Empty; if (attr.DateTimeBehavior == Microsoft.Xrm.Sdk.Metadata.DateTimeBehavior.DateOnly) { behavior = "DateOnly"; } else if (attr.DateTimeBehavior == Microsoft.Xrm.Sdk.Metadata.DateTimeBehavior.TimeZoneIndependent) { behavior = "TimeZoneIndependent"; } else if (attr.DateTimeBehavior == Microsoft.Xrm.Sdk.Metadata.DateTimeBehavior.UserLocal) { behavior = "UserLocal"; } sb.AppendFormat("\t\t\t[DateTimeBehavior(DateTimeBehavior.{0})]\r\n", behavior); } foreach (var relationship in attr.Relationships) { if (this.entityCollection.SelectedDefinitions.Any(d => d.LogicalName == relationship.ReferencedEntity)) { var eC = this.entityCollection[relationship.ReferencedEntity]; sb.AppendFormat("\t\t\t[CrmLookup({0}.EntityName, {0}.Columns.{1}, RelationshipName = ManyToOneRelationships.{2})]\r\n", eC.Name, eC.AttributesCollection[relationship.ReferencedAttribute].Name, relationship.SchemaName); } else if (relationship.ReferencedEntity != "owner") { sb.AppendFormat("\t\t\t[CrmLookup(\"{0}\", \"{1}\", RelationshipName = \"{2}\")]\r\n", relationship.ReferencedEntity, relationship.ReferencedAttribute, relationship.SchemaName); } else if (relationship.ReferencedEntity == "owner") { sb.AppendFormat("\t\t\t[CrmLookup(\"{0}\", \"{1}\", RelationshipName = \"{2}\")]\r\n", relationship.ReferencedEntity, relationship.ReferencedAttribute, relationship.SchemaName); } } sb.AppendFormat("\t\t\tpublic const string {0} = \"{1}\";\r\n\r\n", attr.Name, attr.LogicalName); } sb.AppendLine("\t\t}"); foreach (var def in item.AdditionalClassesCollection.Definitions) { sb.AppendLine(); if (def.IsEnum) { sb.AppendFormat("\t\tpublic enum {0}\r\n", def.Name); } else { sb.AppendLine("\t\t[SuppressMessage(\"Microsoft.Design\", \"CA1034:NestedTypesShouldNotBeVisible\")]"); sb.AppendFormat("\t\tpublic static class {0}\r\n", def.Name); } sb.AppendLine("\t\t{"); if (def.IsEnum) { foreach (var attr in def.Attributes.Definitions.OrderBy(a => a.Value)) { sb.AppendFormat("\t\t\t{0} = {1},\r\n", attr.Name, attr.Value); } } else { foreach (var attr in def.Attributes.Definitions.OrderBy(a => a.Name)) { if (attr.Type == "String") { if (attr is RelationshipAttributeDefinition) { sb.Append($"\t\t\t[Relationship("); var rAttr = attr as RelationshipAttributeDefinition; if (this.entityCollection.SelectedDefinitions.Any(d => d.LogicalName == rAttr.TargetEntityName)) { sb.Append($"{entityCollection[rAttr.TargetEntityName].Name}.EntityName"); } else { sb.Append($"\"{rAttr.TargetEntityName}\""); } sb.Append($", EntityRole.{rAttr.Role}, \"{rAttr.NavigationPropertyName}\", "); if (rAttr.Role == EntityRole.Referencing) { var ec = entityCollection.Definitions.FirstOrDefault(d => d.LogicalName == item.LogicalName); var att = ec?.AttributesCollection.SelectedDefinitions.FirstOrDefault(d => d.LogicalName == rAttr.LookupFieldName); if (att != null) { sb.Append($"{ec.Name}.Columns.{att.Name}"); } else { sb.Append($"\"{rAttr.LookupFieldName}\""); } } else { var ec = entityCollection.SelectedDefinitions.FirstOrDefault(d => d.LogicalName == rAttr.TargetEntityName); var att = ec?.AttributesCollection.SelectedDefinitions.FirstOrDefault(d => d.LogicalName == rAttr.LookupFieldName); if (att != null) { sb.Append($"{ec.Name}.Columns.{att.Name}"); } else { sb.Append($"\"{rAttr.LookupFieldName}\""); } } sb.Append(")]\r\n"); } sb.AppendFormat("\t\t\tpublic const string {0} = \"{1}\";\r\n", attr.Name, attr.Value); } else { sb.AppendFormat("\t\t\tpublic const int {0} = {1};\r\n", attr.Name, attr.Value); } } } sb.AppendLine("\t\t}"); } sb.AppendLine("\t}"); sb.AppendLine("}"); var fileInfo = new FileInfo(string.Format("../../../../Model/Definitions/{0}.cs", item.Name)); File.WriteAllText(fileInfo.FullName, sb.ToString()); string oldFileName = null; if (!string.IsNullOrEmpty(item.PreviousName) && item.PreviousName != item.Name) { oldFileName = string.Format("{0}.cs", item.PreviousName); } fileList.Add(new TfsHelper.FileInfo(fileInfo.Name, oldFileName)); } var fc = new StringBuilder(); fc.AppendLine("using System.ComponentModel;"); fc.AppendLine(); fc.AppendLine("namespace Model"); fc.AppendLine("{"); foreach (var def in EnumDefinitionCollection.Instance.SelectedDefinitions) { fc.AppendLine(); if (def.IsGlobal) { fc.AppendFormat("\t[OptionSetDefinition(\"{0}\")]\r\n", def.LogicalName); } else { var attribute = def.ReferencedBy.First(); fc.AppendFormat("\t[OptionSetDefinition({0}.EntityName, {0}.Columns.{1})]\r\n", attribute.ParentEntity.Name, attribute.Name); } fc.AppendFormat("\tpublic enum {0}\r\n", def.Name); fc.AppendLine("\t{"); if (def.HasNullValue) { fc.AppendLine("\t\tNull = 0,"); } foreach (var val in def.Values.Definitions) { fc.AppendFormat(CultureInfo.InvariantCulture, "\t\t[Description(\"{0}\")]\r\n", val.DisplayName); fc.AppendFormat("\t\t{0} = {1},\r\n", val.Name, val.Value); } fc.AppendLine("\t}"); } fc.AppendLine("}"); File.WriteAllText("../../../../Model/Definitions/OptionSetDefinitions.cs", fc.ToString()); fileList.Add(new TfsHelper.FileInfo("OptionSetDefinitions.cs")); TfsHelper.EnsureReferencesInProjectFile("../../../../Model/Model.projitems", fileList, @"$(MSBuildThisFileDirectory)Definitions"); MessageBox.Show("Definition files generation succeedeed"); }
private void PopulateDependenciesWithLinkQuery(Dictionary <int, DependencyItem> dependenciesModel, Query query, QueryDefinition queryDef) { var queryResults = query.RunLinkQuery(); int successorsCount = 0; DependencyItem tempItem; // Populate the model (parent id's and successors) from the query foreach (WorkItemLinkInfo workItemInfo in queryResults) { if (workItemInfo.SourceId == 0) // parent { if (!dependenciesModel.ContainsKey(workItemInfo.TargetId)) { tempItem = new DependencyItem(workItemInfo.TargetId); dependenciesModel.Add(workItemInfo.TargetId, tempItem); this.Logger.Debug(string.Format(@"[TFS] Got PARENT: {0}", tempItem.ToString())); } } else // child { // ToDo: Make this also work with Predecessors queries if (workItemInfo.LinkTypeId == 3) // successor { // Get the parent dependenciesModel.TryGetValue(workItemInfo.SourceId, out var dependencyItem); if (dependencyItem != null) { dependencyItem.Successors.Add(workItemInfo.TargetId); successorsCount++; } else { this.Logger.Debug(string.Format(@"[TFS] Could not get PARENT: {0} for SUCCESSOR: {1}", workItemInfo.SourceId, workItemInfo.TargetId)); } } } } if (successorsCount == 0) { throw new Exception(string.Format("[TFS] The query '{0}' does not return any successors", queryDef.Name)); } var successorsThatAreNotParents = new List <DependencyItem>(); // Add Title and Tags to items in the DependenciesModel foreach (KeyValuePair <int, DependencyItem> entry in dependenciesModel) { if (entry.Value.Title == null) { var workItem = this.WorkItemStore.GetWorkItem(entry.Key); entry.Value.Title = workItem.Title; entry.Value.State = workItem.State; entry.Value.Comment = Path.GetFileName(workItem.IterationPath); entry.Value.Tags.AddRange(TfsHelper.GetTags(workItem)); } foreach (var successor in entry.Value.Successors) { // If successors are not parents, retrieve them from TFS and add them if (!dependenciesModel.ContainsKey(successor)) { var workItem = this.WorkItemStore.GetWorkItem(successor); var dependencyItem = new DependencyItem(successor) { Title = workItem.Title, State = workItem.State, Comment = Path.GetFileName(workItem.IterationPath) }; dependencyItem.Tags.AddRange(TfsHelper.GetTags(workItem)); successorsThatAreNotParents.Add(dependencyItem); } } } // Add successors That Are Not Parents to the DependenciesModel foreach (var successor in successorsThatAreNotParents) { if (!dependenciesModel.ContainsKey(successor.Id)) { dependenciesModel.Add(successor.Id, successor); this.Logger.Debug(string.Format(@"[TFS] Got SUCCESSOR: {0}", successor.ToString())); } } }
private void UpdateWorkItems(List <int> workItemIds) { foreach (int workItemId in workItemIds) { _logger.Log(LogLevel.Debug, $"\tGetting #{workItemId}... "); var workItem = _tfsCrudManager.GetWorkItem(workItemId); if (workItem == null) { _logger.Log(LogLevel.Error, "ERROR! "); _lastChangedWorkItems.FailureCount++; continue; } _logger.Log(LogLevel.Debug, "Done! "); var fields = workItem["fields"]; var type = fields["System.WorkItemType"].ToString(); var state = fields["System.State"].ToString(); var assignedTo = fields["System.AssignedTo"]; var title = fields["System.Title"].ToString(); string tags = string.Empty; if (fields["System.Tags"] != null) { tags = fields["System.Tags"].ToString(); } _logger.Log(LogLevel.Debug, $"Status of this {type} is {state}, assigned to {assignedTo ?? "Unassigned" }, title is {title}"); var matchedSkipTitle = _titlesToSkip.FirstOrDefault(s => title.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) >= 0); if (matchedSkipTitle != null) { _logger.Log(LogLevel.Debug, $"Skipping, since we have this title in skip list ({matchedSkipTitle})"); continue; } if (type != "Product Backlog Item" && type != "Bug") { _logger.Log(LogLevel.Debug, "Skipping not PBI or Bugs"); continue; } if (state == Constants.Tfs.State.Done.GetDescription()) { _logger.Log(LogLevel.Debug, "Skipping DONE item..."); continue; } if (state == Constants.Tfs.State.Removed.GetDescription()) { _logger.Log(LogLevel.Debug, "Skipping REMOVED item..."); continue; } if (tags.Contains(_readyForTestTag)) { _logger.Log(LogLevel.Debug, $"Skipping already marked as '{_readyForTestTag}' item..."); continue; } string foundUser = null; if (!tags.Contains(_nonTestableTag)) { // Only find tester when it's a Testable item try { foundUser = FindUserToTest(fields, workItem); if (foundUser == null) { _logger.Log(LogLevel.Debug, $"Assigning it to default tester {_defaultTester}... "); foundUser = _defaultTester; } } catch (DeveloperHasNotFinishedTaskException) { _logger.Log(LogLevel.Info, $"There is a non-Done child Development task, Skipping this workItem."); continue; } } if (tags.Contains(_nonTestableTag)) { if (GetChildTasks(workItem) .Any(o => o["fields"]["System.State"].ToString() == Constants.Tfs.State.InProgress.GetDescription() || o["fields"]["System.State"].ToString() == Constants.Tfs.State.ToDo.GetDescription())) { _logger.Log(LogLevel.Debug, $"Skipping setting Done for '{_nonTestableTag}' item... Because there are tasks In Progress or To Do."); continue; } _logger.Log(LogLevel.Debug, $"Setting Done for '{_nonTestableTag}' item... Because all tasks are done."); var result = UpdateWorkItem(new UpdateWorkItemRequest() { AssignedTo = foundUser, ExistingFields = fields, Tags = tags, WorkItemId = workItemId, State = Constants.Tfs.State.Done }); if (result == null) { _logger.Log(LogLevel.Error, "ERROR! "); _lastChangedWorkItems.FailureCount++; continue; } _logger.Log(LogLevel.Debug, "Done!"); continue; } _logger.Log(LogLevel.Debug, $"Adding Ready For Test Tag{(foundUser == null ? "" : " and assigning to user " + foundUser)}... "); tags = TfsHelper.AddTag(tags, _readyForTestTag); var comment = GenerateCommentIfNeeded(); string updateWorkItemResult = UpdateWorkItem(new UpdateWorkItemRequest() { AssignedTo = foundUser, ExistingFields = fields, Tags = tags, WorkItemId = workItemId, Comment = comment }); if (updateWorkItemResult == null) { _logger.Log(LogLevel.Error, "ERROR! "); _lastChangedWorkItems.FailureCount++; continue; } _logger.Log(LogLevel.Debug, "Done!"); } }
private void AddMissingTasksToIds(List <WorkItem> workItems, string developerUserName, string teamTagName) { foreach (var item in workItems) { var currentItemData = GetWorkItem(item); if (currentItemData == null) { _logger.Log(LogLevel.Error, $"Skipping adding Tasks to workItem {item.Id}, since we can't get data for it!"); continue; } _logger.Info($"Adding missing tasks for #{item.Id} (to {developerUserName})."); double effort = 0; var effortObject = currentItemData["fields"]["Microsoft.VSTS.Scheduling.Effort"]; if (effortObject != null) { effort = double.Parse(effortObject.ToString()); } string tags = string.Empty; if (currentItemData["fields"]["System.Tags"] != null) { tags = currentItemData["fields"]["System.Tags"].ToString(); } // Fix title var originalTitle = currentItemData["fields"]["System.Title"].ToString(); _logger.Debug($"Title is {originalTitle}."); var title = originalTitle.Replace(" ", " "); title = Regex.Replace(title, @"\s*->\s*", " → "); var doUpdateOriginalItem = false; if (originalTitle != title) { _logger.Debug($"Fixing title to {title}."); doUpdateOriginalItem = true; } // Add custom tags if (!tags.Contains(teamTagName)) { _logger.Debug($"Adding team Tag {teamTagName}."); doUpdateOriginalItem = true; tags = TfsHelper.AddTag(tags, teamTagName); } if (doUpdateOriginalItem) { _tfsCrudManager.UpdateWorkItem(new UpdateWorkItemRequest() { Title = title, WorkItemId = item.Id, Tags = tags, ExistingFields = currentItemData["fields"] }); } var sprint = currentItemData["fields"]["System.IterationPath"].ToString(); var areaPath = currentItemData["fields"]["System.AreaPath"].ToString(); var teamProject = currentItemData["fields"]["System.TeamProject"].ToString(); var createdBy = currentItemData["fields"]["System.CreatedBy"].ToString(); var cleanedCreatedBy = TfsHelper.GetUserNameFromString(createdBy); if (cleanedCreatedBy != null) { createdBy = cleanedCreatedBy; } var devCreateResult = CreateWorkItem("Dev: " + title, effort, Constants.Tfs.ActivityNames.DevelopmentActivityName, sprint, areaPath, teamProject, developerUserName, item); if (devCreateResult == null) { throw new Exception("Dev Task has not been created!"); } if (tags.Contains(_nonTestableTag)) { _logger.Info($"Skipping QA task creation, because of {_nonTestableTag} tag!"); } else { var qaTaskUser = _defaultTester; if (_qaTeamUsersList.Contains(createdBy)) { _logger.Info($"User who created this item is in QA list, so let's assign QA task for him."); qaTaskUser = createdBy; } var qaEffort = 0; var qaCreateResult = CreateWorkItem("QA: " + title, qaEffort, Constants.Tfs.ActivityNames.TestingActivityName, sprint, areaPath, teamProject, qaTaskUser, item); if (qaCreateResult == null) { throw new Exception("QA Task has not been created!"); } } _logger.Info("Enjoy!"); } }