/// <summary> /// Creates a new work item of a defined type /// </summary> /// <param name="workItemType">The type name</param> /// <param name="title">Default title</param> /// <param name="description">Default description</param> /// <param name="fieldsAndValues">List of extra propierties and values</param> /// <returns></returns> public WorkItem CreateWorkItem(string workItemType, string title, string description, Dictionary<string, object> fieldsAndValues) { WorkItemType wiType = workItemTypeCollection[workItemType]; WorkItem wi = new WorkItem(wiType) { Title = title, Description = description }; foreach (KeyValuePair<string, object> fieldAndValue in fieldsAndValues) { string fieldName = fieldAndValue.Key; object value = fieldAndValue.Value; if (wi.Fields.Contains(fieldName)) wi.Fields[fieldName].Value = value; else throw new ApplicationException(string.Format("Field not found {0} in workItemType {1}, failed to save the item", fieldName, workItemType)); } if (wi.IsValid()) { wi.Save(); } else { ArrayList validationErrors = wi.Validate(); string errMessage = "Work item cannot be saved..."; foreach (Field field in validationErrors) errMessage += "Field: " + field.Name + " has status: " + field.Status + "/n"; throw new ApplicationException(errMessage); } return wi; }
public ArrayList Validate() { return(workItem.Validate()); }
private void ValidateAndSave(WorkItem srcItem, WorkItem copiedItem) { var errors = copiedItem.Validate(); if (errors.Count > 0) { var partialCopyInfos = new List<PartialCopyInfo>(); foreach (Field field in errors) { partialCopyInfos.Add(new PartialCopyInfo { FieldName = field.Name, Value = field.OriginalValue.ToString(), ExpectedValue = field.Value.ToString() }); copiedItem[field.Name] = field.OriginalValue; } _logger.LogPartialCopy(srcItem, copiedItem.Id, partialCopyInfos.ToArray()); } copiedItem.Save(); }
private void updateWorkItemState(Ticket source, WorkItem workItem) { var statesTosave = new List<string>(); if (source.TicketState != Ticket.State.Done) { if (source.TicketState == Ticket.State.InProgress) { statesTosave.Add(tfsStateMap.GetSelectedInProgressStateFor(workItem.Type.Name)); } else if (source.TicketState == Ticket.State.Todo || source.TicketState == Ticket.State.Unknown) { statesTosave.Add(tfsStateMap.GetSelectedApprovedStateFor(workItem.Type.Name)); } if (importSummary.OpenTickets.ContainsKey(source.TicketType) == false) { importSummary.OpenTickets.Add(source.TicketType, 1); } else { importSummary.OpenTickets[source.TicketType]++; } } else { statesTosave = tfsStateMap.GetStateTransistionsToDoneFor(workItem.Type.Name); } foreach (var stateToSave in statesTosave) { workItem.State = stateToSave; var validationErrors = workItem.Validate(); if (validationErrors.Count == 0) { workItem.Save(SaveFlags.MergeLinks); } else { var waring = string.Format("Failed to set state for Work-item {0} - \"{1}\"", workItem.Id, workItem.Title); importSummary.Warnings.Add(waring); var failure = new TfsFailedValidation(source, validationErrors); importSummary.Warnings.Add(" " + failure.Summary); foreach (var issue in failure.Issues) { var fieldInTrouble = string.Format(" * {0} - {1} (Value: {2})", issue.Name, issue.Problem, issue.Value); importSummary.Warnings.Add(fieldInTrouble); foreach (var info in issue.Info) { importSummary.Warnings.Add(" * " + info); } } break; } } }
private void button_save_Click(object sender, EventArgs e) { try { ////http://social.technet.microsoft.com/wiki/contents/articles/3280.tfs-2010-api-create-workitems-bugs.aspx TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(this.textbox_tfsUrl.Text)); WorkItemStore workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); WorkItemTypeCollection workItemTypes = workItemStore.Projects[this.textbox_defaultProject.Text].WorkItemTypes; WorkItemType workItemType = workItemTypes[combobox_workItemType.Text]; // Assign values to each mandatory field var workItem = new WorkItem(workItemType); workItem.Title = textbox_title.Text; workItem.Description = textbox_description.Text; var fieldAssignTo = "System.AssignedTo"; if (combobox_AssignTo.SelectedItem != null && workItem.Fields.Contains(fieldAssignTo)) { workItem.Fields[fieldAssignTo].Value = combobox_AssignTo.Text; } var fieldSeverity="Microsoft.VSTS.Common.Severity"; if (combobox_severity.SelectedItem != null && workItem.Fields.Contains(fieldSeverity)) { workItem.Fields[fieldSeverity].Value = combobox_severity.Text; } var fieldPriority = "Microsoft.VSTS.Common.Priority"; if (workItem.Fields.Contains(fieldPriority)) { workItem.Fields[fieldPriority].Value = textbox_Priority.Text; } if (combobox_AreaPath.SelectedItem != null) { workItem.AreaPath = combobox_AreaPath.Text; } if (combobox_IterationPath.SelectedItem != null) { workItem.IterationPath = combobox_IterationPath.Text; } var fieldState = "System.State"; if (combobox_state.SelectedItem != null && workItem.Fields.Contains(fieldState)) { workItem.Fields[fieldState].Value = combobox_state.Text; } var fieldReason = "System.Reason"; if (combobox_reason.SelectedItem != null && workItem.Fields.Contains(fieldReason)) { workItem.Fields["System.Reason"].Value = combobox_reason.Text; } string fieldSystenInfo = "Microsoft.VSTS.TCM.SystemInfo"; if (workItem.Fields.Contains(fieldSystenInfo)) { if (workItem.Fields[fieldSystenInfo].FieldDefinition.FieldType == FieldType.Html) { workItem.Fields[fieldSystenInfo].Value = textbox_SystemInfo.Text.Replace(Environment.NewLine,"<br/>"); } else { workItem.Fields[fieldSystenInfo].Value = textbox_SystemInfo.Text; } } string fieldsReproStreps = "Microsoft.VSTS.TCM.ReproSteps"; if (workItem.Fields.Contains(fieldsReproStreps)) { workItem.Fields[fieldsReproStreps].Value = textbox_ReproStep.Text; if (string.IsNullOrEmpty(textbox_ReproStep.Text)) { workItem.Fields[fieldsReproStreps].Value = workItem.Description; } } // add image string tempFile = Path.Combine(Environment.CurrentDirectory, this.Filename); File.WriteAllBytes(tempFile, this.ImageData); workItem.Attachments.Add(new Attachment(tempFile)); // Link the failed test case to the Bug // workItem.Links.Add(new RelatedLink(testcaseID)); // Check for validation errors before saving the Bug ArrayList validationErrors = workItem.Validate(); if (validationErrors.Count == 0) { workItem.Save(); if (this.TFSInfo == null) { this.TFSInfo = new TFSInfo(); } this.TFSInfo.ID = workItem.Id.ToString(); this.TFSInfo.Title = workItem.Title; this.TFSInfo.Description = workItem.Description; // http://stackoverflow.com/questions/6466441/how-to-map-a-tfs-item-url-to-something-viewable var testManagementService = tfs.GetService<ILinking>(); this.TFSInfo.WebDetailUrl = testManagementService.GetArtifactUrlExternal(workItem.Uri.ToString()); var myService = tfs.GetService<TswaClientHyperlinkService>(); this.TFSInfo.WebEditUrl = myService.GetWorkItemEditorUrl(workItem.Id).ToString(); if (checkbox_description_addImage.Checked) { if (workItem.Fields["System.Description"].FieldDefinition.FieldType == FieldType.Html) { workItem.Description += string.Format("<br/><a href=\"{0}\"><img src=\"{0}\" /></a>", workItem.Attachments[0].Uri.ToString()); } else { workItem.Description += System.Environment.NewLine + workItem.Attachments[0].Uri.ToString(); } } if (checkbox_reproStep_AddImage.Checked && (workItem.Fields.Contains(fieldsReproStreps))) { if (workItem.Fields[fieldsReproStreps].FieldDefinition.FieldType == FieldType.Html) { workItem.Fields[fieldsReproStreps].Value += string.Format("<br/><a href=\"{0}\"><img src=\"{0}\" /></a>", workItem.Attachments[0].Uri.ToString()); } else { workItem.Fields[fieldsReproStreps].Value += System.Environment.NewLine + workItem.Attachments[0].Uri.ToString(); } } workItem.Save(); this.SetLastValue(); DialogResult = DialogResult.OK; } else { string errrorMsg = "Validation Error in field\n"; foreach (Field field in validationErrors) { errrorMsg += field.Name + "\n"; } MessageBox.Show(errrorMsg); } tfs.Dispose(); // delete temps images System.IO.File.Delete(tempFile); } catch (Exception eError) { MessageBox.Show(eError.ToString()); } }
private static void ValidateAndSaveWorkItem(WorkItem workItem) { if (!workItem.IsValid()) { var invalidFields = workItem.Validate(); var sb = new StringBuilder(); sb.AppendLine("Can't save item because the following fields are invalid: "); foreach (Field field in invalidFields) { sb.AppendFormat("{0}: '{1}'", field.Name, field.Value).AppendLine(); } Logger.ErrorFormat(sb.ToString()); return; } workItem.Save(); }
/// <summary> /// creazione WI /// </summary> /// <param name="tfs"> /// connessione tfs in oggetto /// </param> /// <param name="items"> /// lista di items, dati linguaggio /// </param> /// <param name="tp"> /// progetto in oggetto /// </param> /// <param name="cIS"> /// Configuration Item Software /// </param> public static void CreateWI(TfsTeamProjectCollection tfs, List<string> items, string tp, string cIS) { List<FP> fp = XML.RecuperaFP(); DateTime now = DateTime.Now; double totAlma = 0; double costi = double.Parse(System.Configuration.ConfigurationManager.AppSettings["ConvCost"]); List<FP> linguaggio = new List<FP>(); WorkItemStore store = tfs.GetService<WorkItemStore>(); Project proj = store.Projects[tp]; if (!proj.WorkItemTypes.Contains("QAReport")) { string xmlPath = "wit/QAReport.xml"; System.IO.StreamReader xmlStreamReader = new System.IO.StreamReader(xmlPath); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(xmlStreamReader); System.Xml.XmlElement firstElement = (System.Xml.XmlElement)xmlDoc.DocumentElement; proj.WorkItemTypes.Import(firstElement); } store.RefreshCache(true); proj = store.Projects[tp]; WorkItemType type = proj.WorkItemTypes["QAReport"]; WorkItem workItem = new WorkItem(type); workItem["Title"] = cIS + " " + now; //workItem["CISoftware"] = cIS; workItem["DataD"] = now; CSCount csc = TFS.AllChangeset(tfs, tp); workItem["NChangeset"] = csc.NonAssociato; workItem["AllChangeset"] = csc.All; int i = 0; if (items.Count == 0) { workItem["DescrizioneHtml"] = "<table width='100%'><tr><th style='border-bottom:1px solid black'>Data</th><th style='border-bottom:1px solid black'>Linguaggio</th><th style='border-bottom:1px solid black'>Nr Files</th><th style='border-bottom:1px solid black'>Righe di Codice</th><th style='border-bottom:1px solid black'>Utenti</th></tr><tr>"; } else { workItem["DescrizioneHtml"] = "<table width='100%'><tr><th style='border-bottom:1px solid black'>Data</th><th style='border-bottom:1px solid black'>Linguaggio</th><th style='border-bottom:1px solid black'>Nr Files</th><th style='border-bottom:1px solid black'>Righe di Codice</th><th style='border-bottom:1px solid black'>Utenti</th></tr><tr>"; FP tmp = new FP(); foreach (string item in items) { if (i == 5) { i = 0; workItem["DescrizioneHtml"] += "</tr><tr>"; } if (i == 1) { tmp.Linguaggio = item; } if (i == 3) { tmp.Dato = int.Parse(item); totAlma += tmp.Dato; } workItem["DescrizioneHtml"] += "<td style='border-bottom:1px solid black'>" + item + "</td>"; // workItem.Attachments.Add(new Attachment("")); i++; if (i == 5) { linguaggio.Add(tmp); tmp = new FP(); } } workItem["DescrizioneHtml"] += "</tr></table>"; double valoreFP = XML.AnalisiFP(linguaggio, fp); workItem["FP"] = valoreFP; workItem["ValoreCustom"] = totAlma; workItem["FP Totali"] = FPTotali; workItem["Valore Totale"] = CostiTotali; workItem["ControlloTask"] = TFS.ControlloTask(tfs, tp).ToString(); workItem["ControlloSprint"] = TFS.ControlloSprint(tfs, tp).ToString(); if (TFS.CsNoWI.Count != 0) { workItem["DescrizioneChange"] = "<table width='100%'><tr><th style='border-bottom:1px solid black'>ChangesetID</th><th style='border-bottom:1px solid black'>User</th><th style='border-bottom:1px solid black'>Data Creazione</th><th style='border-bottom:1px solid black'>Commento</th></tr>"; foreach (Change_Data item in TFS.CsNoWI) { workItem["DescrizioneChange"] += "<tr>"; workItem["DescrizioneChange"] += "<td style='border-bottom:1px solid black'><A href='" + tfs.Uri.AbsolutePath + "web/UI/Pages/Scc/ViewChangeset.aspx?changeset=" + item.Id + "'>" + item.Id + "</A></td>"; workItem["DescrizioneChange"] += "<td style='border-bottom:1px solid black'>" + item.User + "</td>"; workItem["DescrizioneChange"] += "<td style='border-bottom:1px solid black'>" + item.Data + "</td>"; if (string.IsNullOrEmpty(item.Comment)) { workItem["DescrizioneChange"] += "<td style='border-bottom:1px solid black'> -- </td>"; } else { workItem["DescrizioneChange"] += "<td style='border-bottom:1px solid black'>" + item.Comment + "</td>"; } workItem["DescrizioneChange"] += "</tr>"; } workItem["DescrizioneChange"] += "</table>"; } } Array result = workItem.Validate().ToArray(); try { workItem.Save(); } catch (Exception e) { Logger.Error(new LogInfo(System.Reflection.MethodBase.GetCurrentMethod(), "INT", string.Format("errore creazione WI: {0}", e.Message))); throw e; } FPTotali = 0; CostiTotali = 0; }
/// <summary> /// Handles the execute command by resolving the provided command parameter /// </summary> public virtual void OkExecuteMethod(object executeCommandParam) { var tfs = ViewModel.TfsConnection; var proj = ViewModel.TfsProject; var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); if (store != null && store.Projects != null) { WorkItemTypeCollection workItemTypes = store.Projects[proj.Name].WorkItemTypes; WorkItemType wit = workItemTypes[ViewModel.ItemType]; var workItem = new WorkItem(wit) { Title = ViewModel.Title, Description = ViewModel.Comment, IterationPath = ViewModel.Iteration, AreaPath = ViewModel.AreaPath, }; workItem["Priority"] = ViewModel.Priority; var assigned = workItem.Fields["Assigned To"]; if (assigned != null) assigned.Value = ViewModel.AssignedTo; // create file attachments foreach (var attach in ViewModel.Attachments.Where(a => a.Chosen)) { workItem.Attachments.Add( new Microsoft.TeamFoundation.WorkItemTracking.Client.Attachment(attach.Path, attach.Comment)); } var validationResult = workItem.Validate(); if (validationResult.Count == 0) { workItem.Save(); if (MessageBox.Show(string.Format("Created bug {0}", workItem.Id)) == MessageBoxResult.OK) Dispose(); } else { var tt = new StringBuilder(); foreach (var res in validationResult) tt.AppendLine(res.ToString()); MessageBox.Show(tt.ToString()); } } }
//save final state transition and set final reason. private bool ChangeWorkItemStatus(WorkItem workItem, string orginalSourceState, string destState, string reason) { //Try to save the new state. If that fails then we also go back to the orginal state. try { workItem.Open(); workItem.Fields["State"].Value = destState; workItem.Fields["Reason"].Value = reason; ArrayList list = workItem.Validate(); workItem.Save(); return true; } catch (Exception) { logger.WarnFormat("Failed to save state for workItem: {0} type:'{1}' state from '{2}' to '{3}' =>rolling workItem status to original state '{4}'", workItem.Id, workItem.Type.Name, orginalSourceState, destState, orginalSourceState); //Revert back to the original value. workItem.Fields["State"].Value = orginalSourceState; return false; } }
/// <summary> /// Gets an ArrayList of fields in this work item that are not valid. /// </summary> /// <returns> /// An ArrayList of the fields in this work item that are not valid. /// </returns> public IEnumerable <IField> Validate() { return(_item.Validate().Cast <Tfs.Field>().Select(field => ExceptionHandlingDynamicProxyFactory.Create <IField>(new FieldProxy(field)))); }