예제 #1
0
 public void AddWorkItem()
 {
     WorkItem newItem = new WorkItem( teamProject.WorkItemTypes["タスク"] );
     newItem.Title = "作業項目の概要です";
     newItem.Description = "作業項目の詳細です";
     newItem.Save();
 }
예제 #2
0
        // Return if Bug is successfully saved or not. Note that Save will cause event that will be
        // triggering our code - but correctly filtered out as done by the functional user.
        public Boolean saveBug(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem)
        {
            try
            {
                workItem.Save();
                HandlerSettings.LogMessage(
                    String.Format("Saved workitem: {0}", workItem.Title),
                    HandlerSettings.LoggingLevel.INFO);
            }
            catch (Exception e)
            {
                // According to doc there are two exceptions that can be thrown:
                //      Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException
                //      Microsoft.TeamFoundation.WorkItemTracking.Client.DeniedOrNotExistException
                // but at least ValidationException is not recognized as subclass to Exception so compile error
                // See http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.workitemtracking.client.workitem.partialopen.aspx

                HandlerSettings.LogMessage(
                    String.Format("Failed to save workitem, error: {0}", e.Message),
                    HandlerSettings.LoggingLevel.ERROR);
                return(false);
            }

            return(true);
        }
예제 #3
0
        /// <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;
        }
예제 #4
0
        public int AddNewWIFromMailBug(MessageRequest data)
        {
            var manager = new TFSConnectionManager();
            //var WIToAdd = GetNewWorkItem(Connection, ProjectName, "BUG", AreaPath, IterationPath, data.Subject, data.Body);

            using (var conn = manager.GetConnection())
            {
                WorkItemStore workItemStore = conn.GetService<WorkItemStore>();
                Project prj = workItemStore.Projects[ProjectName];
                WorkItemType workItemType = prj.WorkItemTypes["BUG"];


                var WIToAdd = new WorkItem(workItemType)
                {
                    Title = data.Subject,
                    Description = data.Body,
                    IterationPath = IterationPath,
                    AreaPath = AreaPath,
                };

                WIToAdd.Fields[this.StepsToReproduceName].Value = data.Body;
                if (!string.IsNullOrWhiteSpace(this.AssignedToValue))
                {
                    WIToAdd.Fields[this.AssignedToName].Value = this.AssignedToValue;
                }

                var filePath = TempFileManager.SaveFileAndGetName(data.FileFormat);
                try
                {
                    WIToAdd.Attachments.Add(new Microsoft.TeamFoundation.WorkItemTracking.Client.Attachment(filePath));
                    WIToAdd.Save();
                    return WIToAdd.Id;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    TempFileManager.ClearFile(filePath);
                }
            }
        }
예제 #5
0
        private void CreateTask(Outlook.MailItem mail)
        {
            string tempPath = Path.GetTempPath();
            string mailTempPath = Path.Combine(tempPath, MakeValidFileName(mail.Subject) + ".msg");

            try
            {
                if (File.Exists(mailTempPath))
                    File.Delete(mailTempPath);

                mail.SaveAs(mailTempPath, Outlook.OlSaveAsType.olMSG);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error saving Mail content", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                using (var tfs = new TfsTeamProjectCollection(new Uri(Settings.Default.TFSUrl)))
                {
                    WorkItemStore wis = tfs.GetService(typeof(WorkItemStore)) as WorkItemStore;

                    var projectQuery = from prj in wis.Projects.Cast<Project>()
                                       where prj.HasWorkItemWriteRights
                                       select prj.Name;

                    var projectForm = new SelectProjectForm(projectQuery);

                    try
                    {
                        var pjResult = projectForm.ShowDialog();

                        if (pjResult != DialogResult.OK)
                            return;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error selecting Team Project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    WorkItem wi = null;

                    try
                    {
                        var project = wis.Projects[projectForm.SelectedProject] as Project;

                        var tasktype = project.WorkItemTypes["Task"];
                        wi = new WorkItem(tasktype);

                        wi.Description = mail.Body;
                        wi.Reason = "New";
                        wi.Title = mail.Subject;

                        wi.Attachments.Add(new Attachment(mailTempPath, "Mail"));

                        foreach (Outlook.Attachment attachment in mail.Attachments)
                        {
                            string fileName = attachment.FileName;
                            int i = 1;

                            while (wi.Attachments.Cast<Attachment>().Where(a => a.Name == fileName).Count() > 0)
                                fileName = string.Format("{0}_{1}.{2}", Path.GetFileNameWithoutExtension(attachment.FileName), i++, Path.GetExtension(attachment.FileName));

                            string attachmentPath = Path.Combine(tempPath, fileName);

                            if (File.Exists(attachmentPath))
                                File.Delete(attachmentPath);

                            attachment.SaveAsFile(attachmentPath);

                            wi.Attachments.Add(new Attachment(attachmentPath, string.Format("Mail Attachment: {0}", attachment.DisplayName)));
                        }

                        wi.IterationPath = project.Name;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error creating Task", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        var wiForm = new WorkItemForm(wi);
                        var wiResult = wiForm.ShowDialog();

                        if (wiResult == DialogResult.OK)
                            wi.Save();

                        wi.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error saving Task", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error connecting to TFS", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #6
0
        /// <summary>
        /// Responsável por criar tarefas de BUG
        /// </summary>
        /// <param name="idBug"></param>
        /// <param name="assignedTo"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public bool CreateBugTask(int idBug, string assignedTo, string title)
        {
            // TODO: Onde está se esperando a exceção? No save?
            try
            {
                var basedOn = GetWorkItem(idBug);

                var task = new WorkItem(project.WorkItemTypes["Task"]);
                //var parent = GetParent(idBug);

                task.Description = string.Format("Verificar o Bug {0}\n\n{1}", basedOn.Title, basedOn.Description);
                task.Fields["Assigned To"].Value = assignedTo;

                basedOn.Fields["Assigned To"].Value = assignedTo;
                basedOn.State = "Active";
                task.Title = title;

                task.Links.Add(new RelatedLink(store.WorkItemLinkTypes.LinkTypeEnds["Parent"], basedOn.Id));
                task.Title = GetTitlePrefix(basedOn, title);

                #region //
                //task.Links.Add(new RelatedLink(store.WorkItemLinkTypes.LinkTypeEnds["Tests"], basedOn.Id));

                //TODO: Existe a possibilidade de um bug não ter tarefa pai?
                /*if (parent != null)
                {
                    task.Links.Add(new RelatedLink(store.WorkItemLinkTypes.LinkTypeEnds["Parent"], parent.Id));
                    task.Title = GetTitlePrefix(parent, title);
                }*/

                //for (int i = 0; i < basedOn.WorkItemLinks.Count; i++)
                //{
                //    if (basedOn.WorkItemLinks[i].LinkTypeEnd.Name.Equals("Parent"))
                //    {
                //        parentId = basedOn.WorkItemLinks[i].TargetId;
                //        task.Links.Add(new RelatedLink(store.WorkItemLinkTypes.LinkTypeEnds["Parent"], basedOn.WorkItemLinks[i].TargetId));
                //        break;
                //    }
                //}
                #endregion

                basedOn.Save();
                task.Save();

                return true;
            }
            catch
            {
                return false;
            }
        }
예제 #7
0
        /// <summary>
        /// Método responsável por alterar os status de um workitem
        /// </summary>
        /// <param name="wi">Workitem Alterado</param>
        /// <param name="taskState">Novo status</param>
        /// <param name="comments">Comentários</param>
        /// <param name="bugReason">Razão de fechamento do BUG</param>
        private void ChangeTaskStatus(WorkItem wi, string taskState, string comments, string taskReason, string bugReason)
        {
            var linkedBug = default(WorkItem);

            if (taskState == "Closed" && wi.State != "Closed")
            {
                linkedBug = GetBugByTaskId(wi.Id);

                if (linkedBug != null)
                {
                    linkedBug.Fields["Assigned To"].Value = linkedBug.CreatedBy;
                    linkedBug.State = "Resolved";
                    linkedBug.Fields["Reason"].Value = bugReason;
                    linkedBug.History = comments;
                }
            }

            wi.State = taskState;
            if (taskReason != String.Empty)
                wi.Reason = taskReason;
            wi.History = comments;

            wi.Save();

            if (linkedBug != null)
                linkedBug.Save();
        }
예제 #8
0
 /// <summary>
 /// Link Work Items in TFS
 /// </summary>
 /// <param name="source">
 /// The source.
 /// </param>
 /// <param name="targetWorkItemId">
 /// The target Work Item Id.
 /// </param>
 /// <param name="linkTypeEndName">
 /// The link Type End Name.
 /// </param>
 /// <param name="comments">
 /// The comments.
 /// </param>
 public void LinkWorkItems(WorkItem source, int targetWorkItemId, string linkTypeEndName, string comments)
 {
     WorkItem wItem = tfsManager.GetWorkItem(targetWorkItemId);
     if (wItem != null)
     {
         WorkItemLinkTypeEnd linkTypeEnd = tfsManager.GetAllWorkItemLinksTypes().LinkTypeEnds[linkTypeEndName];
         var link = new RelatedLink(linkTypeEnd, targetWorkItemId) { Comment = comments };
         source.Links.Add(link);
         source.Save();
     }
 }
예제 #9
0
        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();
        }
예제 #10
0
        private void updateWorkItem(Ticket source, WorkItem workItem)
        {
            var ticketTitle = workItem.Id + " - " + workItem.Title;
            onDetailedProcessing(ticketTitle);

            if (source.HasParent)
            {
                var parentWorkItem = findWorkItem(source.Parent);
                if (parentWorkItem != null)
                {
                    try
                    {
                        var workItemStore = (WorkItemStore) tfs.GetService(typeof (WorkItemStore));
                        var linkType = workItemStore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy];
                        parentWorkItem.Links.Add(new WorkItemLink(linkType.ForwardEnd, workItem.Id));
                    }
                    catch (Exception linkException)
                    {
                        importSummary.Warnings.Add(string.Format("Failed to update parent link for '{0}'.", ticketTitle));
                        importSummary.Warnings.Add(linkException.Message);
                    }
                }
            }

            if (source.HasLinks)
            {
                var workItemStore = (WorkItemStore) tfs.GetService(typeof (WorkItemStore));
                if (workItemStore.WorkItemLinkTypes.Contains("System.LinkTypes.Related"))
                {
                    var linkType = workItemStore.WorkItemLinkTypes["System.LinkTypes.Related"];
                    var linkTypeEnd = workItemStore.WorkItemLinkTypes.LinkTypeEnds[linkType.ForwardEnd.Name];
                    foreach (var link in source.Links)
                    {
                        var linkedWorkItem = findWorkItem(link.LinkedTo);
                        if (linkedWorkItem != null)
                        {
                            try
                            {
                                var relatedLink = new RelatedLink(linkTypeEnd, linkedWorkItem.Id);
                                relatedLink.Comment = link.LinkName;
                                workItem.Links.Add(relatedLink);
                            }
                            catch (Exception linkException)
                            {
                                if (linkException.Message.Contains("TF237099") == false)
                                {
                                    importSummary.Warnings.Add(string.Format("Failed to update links for '{0}'.",
                                        ticketTitle));
                                    importSummary.Warnings.Add(linkException.Message);
                                }
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(source.Epic) == false)
            {
                var workItemStore = (WorkItemStore) tfs.GetService(typeof (WorkItemStore));
                var feature = findWorkItem(source.Epic);
                if (feature != null)
                {
                    try
                    {
                        var linkType = workItemStore.WorkItemLinkTypes["System.LinkTypes.Hierarchy"];
                        var linkTypeEnd = workItemStore.WorkItemLinkTypes.LinkTypeEnds[linkType.ReverseEnd.Name];
                        var relatedLink = new RelatedLink(linkTypeEnd, feature.Id);
                        relatedLink.Comment = string.Format("A member of Epic '{0} - {1}'.", feature.Id, feature.Title);
                        workItem.Links.Add(relatedLink);
                    }
                    catch (Exception linkException)
                    {
                        if (linkException.Message.Contains("TF237099") == false)
                        {
                            importSummary.Warnings.Add(string.Format("Failed to update epic link for '{0}'.",
                                ticketTitle));
                            importSummary.Warnings.Add(linkException.Message);
                        }
                    }
                }
            }

            if (workItem.IsDirty)
            {
                try
                {
                    workItem.Save(SaveFlags.MergeLinks);
                }
                catch (Exception ex)
                {
                    importSummary.Errors.Add(
                        string.Format("Failed to update work item '{0} - {1}'.", workItem.Id, workItem.Title));
                    importSummary.Errors.Add(ex.Message);
                    return;
                }
            }

            updateWorkItemState(source, workItem);
        }
예제 #11
0
        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());
            }
        }
        //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;
            }
        }
예제 #13
0
 /// <summary>
 /// Saves any pending changes on this work item.
 /// </summary>
 public void Save()
 {
     _item.Save();
 }
예제 #14
0
파일: TFS.cs 프로젝트: ricred/PivotalTFS
 public void UpdateWorkItem(WorkItem workitem)
 {
     workitem.Save();
 }
예제 #15
0
        private static void AddPivotalTasksAsLinkedWorkItems(WorkItemTypeCollection workItemTypes, WorkItem workItem,
		                                                     Story pivotalStoryToAdd)
        {
            if (pivotalStoryToAdd.Tasks == null)
                return;
            foreach (var task in pivotalStoryToAdd.Tasks.tasks)
            {
                var workitemTask = new WorkItem(workItemTypes[SprintBacklogItem])
                    {
                        Title = task.Description,
                        IterationPath = workItem.IterationPath
                    };
                workitemTask.Fields[HistoryField].Value = workItem.Fields[HistoryField].Value;
                workitemTask.Save();
                workItem.Links.Add(new RelatedLink(workitemTask.Id));
            }
        }
예제 #16
0
        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();
        }
예제 #17
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());
         }
     }
 }
예제 #18
0
        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;
                }
            }
        }
예제 #19
0
 private void UpdateBackLogItemLink(WorkItem backlogItem, WorkItemLink taskLink1)
 {
     backlogItem.Links.Add(taskLink1);
     AddLog("updating backlogworkitem link - " + taskLink1.TargetId.ToString() + "- " + taskLink1.SourceId.ToString());
     backlogItem.Save();
 }
예제 #20
0
        /// <summary>
        /// The add step for work item "Test Case".
        /// </summary>
        /// <param name="dataObject"></param>
        /// <param name="workItem"></param>
        public void AddStep(IDataObject dataObject, WorkItem workItem, out bool comment,bool isAddStep)
        {
            var popup = new StepActionsResult();
            string temp = Regex.Replace(dataObject.GetData(DataFormats.Text).ToString(), @"\s+", " ");
            popup.action.Text = temp;
            popup.Create(null, Icons.AddDetails);
            ITestManagementService testService = collection.GetService<ITestManagementService>();
            var project = testService.GetTeamProject(workItem.Project.Name);
            var testCase = project.TestCases.Find(workItem.Id);
            var step = testCase.CreateTestStep();

            if (!popup.IsCanceled)
            {
                switch (tfsVersion)
                {
                    case TfsVersion.Tfs2011:

                        step.Title = "<div><p><span>" + popup.action.Text + "</span></p></div>";
                        step.ExpectedResult = "<div><p><span>" + popup.expectedResult.Text + "</span></p></div>";


                        //step.Title = popup.action.Text;
                        //step.ExpectedResult = popup.expectedResult.Text;

                        break;
                    case TfsVersion.Tfs2010:

                        step.Title = popup.action.Text;
                        step.ExpectedResult = popup.expectedResult.Text;

                        break;
                }
                if (isAddStep)
                {
                    testCase.Actions.Add(step);
                }
                else
                {
                    testCase.Actions.Clear();
                    testCase.Actions.Add(step);
                }
                testCase.Save();
                workItem.Save();
                comment = true;
            }
            else
            {
                comment = false;
            }
        }
예제 #21
0
        private WorkItem CreateTask(Project project, string taskTitle, string iterationPath)
        {
            // Create the tasks
            var taskType = project.WorkItemTypes["Task"];
            var task = new WorkItem(taskType);
            task.IterationPath = iterationPath;
            //task.State = "New";

            task.Title = taskTitle;
            task.Save();

            AddLog("created task - " + task.Id.ToString());
            return task;
        }
예제 #22
0
 public void Save()
 {
     workItem.Save();
 }
예제 #23
0
        /// <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;
        }