private async Task<float> GetAverageForType(ApplicationUser student, IEnumerable<WorkItem> workItems, WorkItemType type, GradeDistribution distribution) { var scoreUnitManager = new ScoreUnitManager(_db); var workItemsForType = workItems.Where(wi => wi.Type == type); var PointsForType = MaxPointsForType(type, distribution); // If no WorkItem for the type, return total for that type if(workItemsForType.Count() == 0) { return PointsForType; } bool hasGradedScoreUnit = false; float studentsScores = 0.0f; float total = 0.0f; foreach(var workItem in workItemsForType) { var scoreUnit = await scoreUnitManager.GetStudentScoreUnit(workItem, student); if(scoreUnit != null && scoreUnit.Grade.HasValue) { hasGradedScoreUnit = true; studentsScores += scoreUnit.Grade.Value; total += workItem.MaxPoints; } } // If no ScoreUnit has been graded, return the total for that type if(!hasGradedScoreUnit) { return PointsForType; } return (studentsScores / total) * PointsForType; }
private int GetWorkItemsForLastNDays(string noOfDays = "30") { WorkItemType workItemType = project.WorkItemTypes["Bug"]; WorkItemCollection collection = store.Query("SELECT [System.Id],[System.Title],[System.State],[System.CreatedDate] FROM WorkItems WHERE [System.CreatedDate] >= " + "@" + "Today-" + noOfDays); return(collection.Count); }
private static WorkItem CreateWorkItem(Project project, string workItemType) { LipsumGenerator gen = new LipsumGenerator(); Random rnd = new Random(); WorkItemType wiType = project.WorkItemTypes[workItemType]; // Create the work item. WorkItem work = new WorkItem(wiType) { Title = string.Join(" ", gen.GenerateWords(4)), Description = gen.GenerateLipsum(4, Features.Sentences, "") }; if (workItemType == "Task") { work.Fields["Remaining Work"].Value = rnd.Next(2, 10); } else if (workItemType == "Product Backlog Item" || workItemType == "Bug") { work.Fields["Effort"].Value = rnd.Next(1, 13); } // Save the new user story. work.Save(); Count++; return(work); }
private WorkItemCollection GetWorkItemsByState(string state = "New") { WorkItemType workItemType = project.WorkItemTypes["Bug"]; WorkItemCollection collection = store.Query("SELECT [System.Id],[System.Title],[System.State],[System.CreatedDate] FROM WorkItems WHERE [System.State] = '" + state + "'"); return(collection); }
private void button2_Click(object sender, System.EventArgs e) { //Configure credentials ICredentials credentials = new NetworkCredential(this.txtLogin.Text, this.txtPassword.Text, this.txtDomain.Text); //Create the team foundation server class TeamFoundationServer teamFoundationServer = new TeamFoundationServer("http://inflectrasvr03:8080/", credentials); //Get access to the work item store WorkItemStore workItemStore = new WorkItemStore(teamFoundationServer); try { //Create the new work item Project project = workItemStore.Projects["Library Information System"]; WorkItemType workItemType = project.WorkItemTypes["Bug"]; WorkItem workItem = new WorkItem(workItemType); //workItem.AreaId = 1; workItem.Title = "SpiraTest Imported bug"; workItem.Description = "Test description from SpiraTest"; workItem.State = "Active"; workItem.Reason = "New"; workItem["Issue"] = "No"; //workItem[CoreField.CreatedBy] = "Administrator"; //workItem[CoreField.ChangedDate] = DateTime.Now; workItem.Save(); this.textBox1.Text = workItem.Id.ToString(); } catch (Exception exception) { this.textBox1.Text = exception.Message + "\nStack Trace:\n" + exception.StackTrace; } }
/// <summary> /// 创建工作项 /// </summary> /// <param name="type">工作项类型</param> /// <returns>工作项</returns> public WorkItem CreateWorkItem(string type) { WorkItemType itemtype = this.Project.WorkItemTypes[type]; WorkItem workitem = new WorkItem(itemtype); return(workitem); }
private string GetExecutor(WorkItemType type) { var users = _users; IEnumerable <string> roleIds; bool mayBeEmpty = false; switch (type) { case WorkItemType.Project: case WorkItemType.Stage: roleIds = _roles.Where(x => x.RoleCode == RoleType.Director || x.RoleCode == RoleType.MainProjectEngeneer).Select(x => x.Id); users = users.Where(x => x.Roles.Any(r => roleIds.Contains(r.Id))).ToList(); break; case WorkItemType.Partition: case WorkItemType.Task: mayBeEmpty = true; roleIds = _roles.Where(x => x.RoleCode == RoleType.Manager || x.RoleCode == RoleType.Executor).Select(x => x.Id); users = users.Where(x => x.Roles.Any(r => roleIds.Contains(r.Id))).ToList(); break; } var isEmpty = mayBeEmpty && _random.Next(0, 4) == 0; return(isEmpty ? null : users[_random.Next(0, users.Count)].Id); }
public void Copy_UnitTest1() { IWorkItem instance = GetTestWorkItem(); WorkItemType targetType = FindWorkItemType("Task"); instance.Copy(WorkItemTypeWrapper.GetWrapper(targetType)); }
/* Compare work item type definitions and add fields from source work item types and replace workflow */ public void SetFieldDefinitions(WorkItemTypeCollection workItemTypesSource, Hashtable fieldList) { foreach (WorkItemType workItemTypeSource in workItemTypesSource) { WorkItemType workItemTypeTarget = null; if (workItemTypeSource.Name == "User Story") { workItemTypeTarget = workItemTypes["Product Backlog Item"]; } else if (workItemTypeSource.Name == "Issue") { workItemTypeTarget = workItemTypes["Impediment"]; } else { workItemTypeTarget = workItemTypes[workItemTypeSource.Name]; } XmlDocument workItemTypeXmlSource = workItemTypeSource.Export(false); XmlDocument workItemTypeXmlTarget = workItemTypeTarget.Export(false); workItemTypeXmlTarget = AddNewFields(workItemTypeXmlSource, workItemTypeXmlTarget, (List <object>)fieldList[workItemTypeTarget.Name]); try { WorkItemType.Validate(store.Projects[projectName], workItemTypeXmlTarget.InnerXml); store.Projects[projectName].WorkItemTypes.Import(workItemTypeXmlTarget.InnerXml); } catch (XmlException) { logger.Info("XML import falied for " + workItemTypeSource.Name); } } }
internal IEnumerable <int> GetWorkItems(Guid projectId, WorkItemType workItemType) { return(DataContext.WorkItems .Where(w => w.ProjectId == projectId && w.WorkItemType == (int)workItemType) .Select(i => i.WorkItemId) .Distinct()); }
public WorkItem GetNewWorkItem(TfsTeamProjectCollection conn, string projectName, string WIType, string areaPath, string iterationPath, string title, string description) { try { WorkItemStore workItemStore = conn.GetService <WorkItemStore>(); Project prj = workItemStore.Projects[projectName]; WorkItemType workItemType = prj.WorkItemTypes[WIType]; var WIToAdd = new WorkItem(workItemType) { Title = title, Description = description, IterationPath = iterationPath, AreaPath = areaPath, }; return(WIToAdd); } catch (Exception ex) { Logger.Fatal(new LogInfo(MethodBase.GetCurrentMethod(), "ERR", string.Format("Si è verificato un errore durante la creazione del work Item. Dettagli: {0}", ex.Message))); throw ex; } }
public WorkItem( WorkItemReference reference, WorkItemType type, string title, string epicId, decimal?storyPoints = null, string sprint = null, string assignee = null, WorkItemReference parentReference = null) { if (string.IsNullOrEmpty(title)) { throw new ArgumentException("Value cannot be null or empty.", nameof(title)); } if (string.IsNullOrEmpty(epicId)) { throw new ArgumentException("Value cannot be null or empty.", nameof(epicId)); } Reference = reference ?? throw new ArgumentNullException(nameof(reference)); Type = type; Title = title; StoryPoints = storyPoints; Sprint = sprint; EpicId = epicId; Assignee = assignee; ParentReference = parentReference; }
internal int GetWorkItem(Guid projectId, WorkItemType workItemType) { return(DataContext.WorkItems .Where(w => w.ProjectId == projectId && w.WorkItemType == (int)workItemType) .Select(i => i.WorkItemId) .FirstOrDefault()); }
static void Main(string[] args) { if (args.Length != 6) { Console.WriteLine("Usage :"); Console.WriteLine("\t WitdDiff.exe sourceServerName sourceTeamProjectName sourceWitName targetServerName targetTeamProjectName targetWitName"); Console.WriteLine("\t Ex) WitdDiff.exe server1 tp1 Bug1 server2 tp2 Bug2"); Environment.Exit(0); } string sourceServer = args[0]; string sourceTP = args[1]; string sourceWitName = args[2]; string targetServer = args[3]; string targetTP = args[4]; string targetWitName = args[5]; WorkItemType srcWit = GetWorkItemType(sourceServer, sourceTP, sourceWitName); WorkItemType tarWit = GetWorkItemType(targetServer, targetTP, targetWitName); SymDiff <string> witFieldDiff = GetWitFieldDiff(srcWit, tarWit); PrintFieldDiff(witFieldDiff, srcWit, tarWit); PrintRequiredFields(srcWit); PrintRequiredFields(tarWit); }
private static SymDiff <string> GetWitFieldDiff(WorkItemType srcWit, WorkItemType tarWit) { List <string> srcWitFields = new List <string>(); foreach (FieldDefinition fd in srcWit.FieldDefinitions) { srcWitFields.Add(fd.ReferenceName); } srcWitFields.Sort(); List <string> tarWitFields = new List <string>(); foreach (FieldDefinition fd in tarWit.FieldDefinitions) { tarWitFields.Add(fd.ReferenceName); } tarWitFields.Sort(); SymDiff <string> fieldDiff = new SymDiff <string>( srcWitFields.ToArray(), tarWitFields.ToArray(), StringComparer.InvariantCulture); return(fieldDiff); }
/// <summary> /// The add work item for current project. /// </summary> /// <param name="projectName"> /// The project name. /// </param> /// <param name="title"> /// The title. /// </param> /// <param name="workItemTypeString"> /// The work item type string. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public static int AddWorkItemForCurrentProject(string projectName, string title, string workItemTypeString, string areapath = "", string linkend = "", int linkid = 0, string DocUrl = "") { WorkItemType workItemType = TfsManager.Instance.ItemsStore.Projects[projectName].WorkItemTypes[workItemTypeString]; var wi = new WorkItem(workItemType) { Title = title }; if (areapath != "" && areapath != projectName) { wi.AreaPath = areapath; } var requiredFields = GetRequiredFieldsForWorkItem(wi); var popup = new RequiredFields { DataContext = requiredFields }; if (requiredFields.Count != 0) { //Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone(); //Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy"; popup.Create(null, Icons.AddNewWorkItem); if (popup.IsCancelled && !popup.IsCreated) { return(0); } } if (!SetRequiredFieldsForWorkIetm(requiredFields, wi)) { return(0); } if (linkend != "" && linkid > 0) { if (TfsManager.Instance.ItemsStore.WorkItemLinkTypes.LinkTypeEnds.Contains(linkend)) { WorkItemLinkTypeEnd linkTypeEnd = TfsManager.Instance.ItemsStore.WorkItemLinkTypes.LinkTypeEnds[linkend]; wi.Links.Add(new RelatedLink(linkTypeEnd, linkid)); } } if (DocUrl != "") { wi.Links.Add(new Hyperlink(DocUrl)); } var _save_errors = wi.Validate(); if (_save_errors.Count > 0) { return(0); } wi.Save(); return(wi.Id); }
} // end of Generatexml /// <summary> /// Create the default control of type "FieldControl" in the FORM /// </summary> /// <param name="label">Label of the control</param> /// <param name="fldName">Actual field name</param> /// <param name="cqFieldType">Field Type</param> /// <returns></returns> private static ControlType CreateDefaultControl(string label, string fldName, FieldType cqFieldType, WorkItemType wit) { if (CQConstants.FixedFormFields.ContainsKey(fldName)) { // generate the field in FORM only if it is not already there in Fixed Form section return(null); } ControlType ctrl = new ControlType(); ctrl.LabelPosition = new LabelPositionType(); ctrl.LabelPosition = LabelPositionType.Left; ctrl.Label = CQConverterUtil.ValidateXmlString(label); ctrl.FieldName = fldName; if (cqFieldType != FieldType.PlainText) { ctrl.Type = Const.GenericControl; } else { ctrl.Type = Const.HtmlControl; } if (wit != null) { wit.FORM.Layout.WITDItems.Add(ctrl); } return(ctrl); } // end of createdefaultcontrol
public async Task <IActionResult> Edit(int id, [Bind("Name,Id")] WorkItemType workItemType) { if (id != workItemType.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(workItemType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WorkItemTypeExists(workItemType.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(workItemType)); }
public object Convert(object value, Type targetType, object parameter, string language) { WorkItem item = (WorkItem)value; WorkItemType type = item.Type; switch (type) { case WorkItemType.Bug: if (((item.State == State.Resolved) || (item.State == State.Closed)) && (ResolvedBug != null)) { return(ResolvedBug); } return(Bug); case WorkItemType.Task: if ((item.State == State.Completed) && (CompletedTask != null)) { return(CompletedTask); } if ((item.IterationPath != Logic.TeamSettings.IterationPath) && (FutureTask != null)) { return(FutureTask); } return(Task); } throw new ArgumentException(); }
public async Task <IActionResult> Edit(int id, [Bind("Id,AlimTarihi,AlinanKisi,TeslimAlan,Marka,TeslimAlinanAdet,WorkItemsId")] WorkItemType workItemType) { if (id != workItemType.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(workItemType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WorkItemTypeExists(workItemType.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["WorkItemsId"] = new SelectList(_context.WorkItems, "Id", "Id", workItemType.WorkItemsId); return(View(workItemType)); }
private int GetWorkItemsByTitle(string searchText = "Reason: Other", string noOfDays = "30") { WorkItemType workItemType = project.WorkItemTypes["Bug"]; WorkItemCollection collection = store.Query("SELECT [System.Id],[System.Title],[System.State],[System.CreatedDate] FROM WorkItems WHERE [System.Title] CONTAINS '" + searchText + "'" + "AND [System.CreatedDate] >= " + "@" + "Today-" + noOfDays); return(collection.Count); }
public HttpResponseMessage CreateItem([FromUri] string requestedCollectionUri, [FromUri] string requestedProject, [FromBody] SimpleWorkItem requestedWorkItem) { Uri collectionUri = new Uri(requestedCollectionUri); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri, new NetworkCredential(username, password, domain)); WorkItemStore workItemStore = tpc.GetService <WorkItemStore>(); Project teamProject = workItemStore.Projects[requestedProject]; WorkItemType workItemType = teamProject.WorkItemTypes[Utils.GetTFSType(requestedWorkItem.Type)]; // Create the work item. WorkItem newWorkItem = new WorkItem(workItemType) { // The title is generally the only required field that doesn’t have a default value. // You must set it, or you can’t save the work item. If you’re working with another // type of work item, there may be other fields that you’ll have to set. Title = requestedWorkItem.Title, AreaPath = requestedWorkItem.AreaPath, State = requestedWorkItem.State, IterationPath = requestedWorkItem.IterationPath, }; RelatedLink parent = new RelatedLink(workItemStore.WorkItemLinkTypes.LinkTypeEnds[requestedWorkItem.LinkType], requestedWorkItem.LinkId); newWorkItem.Links.Add(parent); newWorkItem.Save(); requestedWorkItem.id = newWorkItem.Id; return(Request.CreateResponse <SimpleWorkItem>(HttpStatusCode.OK, requestedWorkItem)); }
static void Main(string[] args) { // Connect to the server and the store, and get the WorkItemType object // for user stories from the team project where the user story will be created. Uri collectionUri = (args.Length < 1) ? new Uri("http://localhost:8080/tfs/DefaultCollection") : new Uri(args[0]); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri); WorkItemStore workItemStore = tpc.GetService <WorkItemStore>(); Project teamProject = workItemStore.Projects["SandboxProject"]; //WorkItemType workItemType = teamProject.WorkItemTypes["User Story"]; WorkItemType workItemType = teamProject.WorkItemTypes["Test Plan"]; // Create the work item. WorkItem userStory = new WorkItem(workItemType) { // The title is generally the only required field that doesn’t have a default value. // You must set it, or you can’t save the work item. If you’re working with another // type of work item, there may be other fields that you’ll have to set. Title = "Recentlyorderedmenu", Description = "New Test Plan" }; // Save the new user story. userStory.Save(); }
private static void CreateFeatureTestTasks(string uri, string projectName, WorkItemType wIType, WorkItemLinkType hierarchyLinkType) { int parentID = 904830; string titlePrefix = @"LIBS-15-7 driver-instance-global connect"; Console.WriteLine(titlePrefix + " tasks start."); string areaPath = @"TIA\Development\HMI Runtime Innovation Line\IOWA Runtime Innovation Line Platform\Integrationstest\FeatureTest"; string iterationPath = @"TIA\IOWA\Backlog"; // string iterationPath = @"TIA\IOWA\IOWA 2015\Inc 25 (31.08.2013)"; string tags = "DevRelease5"; //string tags = string.Empty; //string assignedTo = "Palotas Gergely"; // string assignedTo = "Csepe Zsombor"; //string assignedTo = "Kiss Zoltan2-Miklos"; string assignedTo = string.Empty; // CreateTask(parentID, titlePrefix + ": KickOff meeting", wIType, hierarchyLinkType, areaPath, iterationPath, 1, 50, tags, assignedTo ); CreateTask(parentID, titlePrefix + ": Create TestSpec.", wIType, hierarchyLinkType, areaPath, iterationPath, 24, 50, tags, assignedTo); CreateTask(parentID, titlePrefix + ": Review meeting TestSpec.", wIType, hierarchyLinkType, areaPath, iterationPath, 1, 50, tags, assignedTo); CreateTask(parentID, titlePrefix + ": Rework TestSpec. after review", wIType, hierarchyLinkType, areaPath, iterationPath, 16, 50, tags, assignedTo); CreateTask(parentID, titlePrefix + ": Testcase implementation Rank1 + Review", wIType, hierarchyLinkType, areaPath, iterationPath, 32, 50, tags, assignedTo); CreateTask(parentID, titlePrefix + ": Testcase implementation", wIType, hierarchyLinkType, areaPath, iterationPath, 32, 50, tags, assignedTo); CreateTask(parentID, titlePrefix + @": BranchTest/IntegrationTest", wIType, hierarchyLinkType, areaPath, iterationPath, 24, 50, tags, assignedTo); Console.WriteLine(titlePrefix + " tasks are ready. Press Enter to close this window."); Console.ReadLine(); }
/// <summary> /// /// </summary> /// <param name="parentID"></param> /// <param name="title"></param> /// <param name="wIType"></param> /// <param name="hierarchyLinkType"></param> private static void CreateTask(int parentID, string title, WorkItemType wIType, WorkItemLinkType hierarchyLinkType, string areaPath, string iterationPath, int workingHours, int stackRank, string tags, string assignedTo) { WorkItem workItem = new WorkItem(wIType); workItem.Title = title; workItem.AreaPath = areaPath; workItem.IterationPath = iterationPath; //Set user story as parent of new task workItem.Links.Add(new WorkItemLink(hierarchyLinkType.ReverseEnd, parentID)); //if (String.IsNullOrEmpty(assignedTo)) // workItem.Fields["Assigned to"].Value = workItem.ChangedBy; //else workItem.Fields["Assigned to"].Value = assignedTo; workItem.Fields["Original estimate"].Value = workingHours; workItem.Fields["Remaining work"].Value = workingHours; workItem.Fields["Stack rank"].Value = stackRank; workItem.Fields["Tags"].Value = tags; System.Collections.ArrayList result = workItem.Validate(); if (result.Count > 0) { Console.WriteLine("There was an error adding this work item to the work item repository."); } else { workItem.Save(); } }
private WorkItem GetDummyWorkItem(WorkItemType type = null) { if (_targetDummyWorkItem == null) { if (_targetProject.WorkItemTypes.Count == 0) { return(null); } if (type == null) { type = _targetProject.WorkItemTypes["Task"]; } if (type == null) { type = _targetProject.WorkItemTypes[0]; } _targetDummyWorkItem = type.NewWorkItem(); _targetDummyWorkItem.Title = TargetDummyWorkItemTitle; _targetDummyWorkItem.Save(); Log.LogDebug("EmbededImagesRepairEnricher: Dummy workitem {id} created on the target collection.", _targetDummyWorkItem.Id); //_targetProject.Store.DestroyWorkItems(new List<int> { _targetDummyWorkItem.Id }); } return(_targetDummyWorkItem); }
private WorkItem(Workspace onwer, FileInfo?file, DirectoryInfo?directory, WorkItemType type) { Onwer = onwer; File = file; Directory = directory; Type = type; Id = Guid.NewGuid(); }
public WorkItem GetNewWorkItem(string type) { WorkItemType workItemType = workItemProject.WorkItemTypes[type]; return(new WorkItem(workItemType) { }); }
/// <summary> /// Returns a JSON string containing all Reasons for provided state. /// </summary> public ActionResult GetReasonsForNewItem(string workItemType) { WorkItemType type = UserContext.Current.CurrentProject.WorkItemTypes.FirstOrDefault(w => w.Name.ToLower() == workItemType); QueryManager manager = new QueryManager(); return(Json(manager.GetAllowedValuesForState("Reason", type), JsonRequestBehavior.AllowGet)); }
public void Copy_UnitTest2() { IWorkItem instance = GetTestWorkItem(); WorkItemType targetType = FindWorkItemType("Task"); const IWorkItemCopyFlags flags = IWorkItemCopyFlags.None; instance.Copy(WorkItemTypeWrapper.GetWrapper(targetType), flags); }
public ComparisionDataSet(IComparable activeEntity, IComparable previousEntity, WorkItemType workItemType, Guid id) { ActiveEntity = activeEntity; PreviousEntity = previousEntity; WorkItemType = workItemType; Guid = id; }
private async Task<BugGuardianResponse> AddWorkItemAsync(WorkItemType workItemType, Exception ex, string message, IEnumerable<string> tags) { var exceptionHash = Helpers.ExceptionsHelper.BuildExceptionHash(ex); WorkItemData bugData = null; //Check if aready reported if (Factories.ConfigurationFactory.AvoidMultipleReport) bugData = await Helpers.WorkItemsHelper.GetExistentWorkItemId(exceptionHash, workItemType, _account); //Create or Update Work Item if (bugData?.ID > 0) return await Helpers.WorkItemsHelper.UpdateWorkItem(bugData, _account); return await Helpers.WorkItemsHelper.CreateNewWorkItem(workItemType, ex, _account, message, tags); }
private float MaxPointsForType(WorkItemType type, GradeDistribution distribution) { switch(type) { case WorkItemType.Exam: return distribution.Exam; case WorkItemType.Project: return distribution.Project; case WorkItemType.Homework: return distribution.Homework; case WorkItemType.Quiz: return distribution.Quiz; case WorkItemType.Other: return distribution.Other; default: return 0; } }
public void QuickCreate(WorkItemType type) { var item = new WorkItem(); item.Fields["System.Title"] = "Bug with snapshot"; item.Fields["System.AssignedTo"] = "Ashirvad Sahu"; item.Rev = 1; //create attachment byte[] content = GetBytesFromFile(@"C:\Users\Ashirvad\Desktop\thX4SG17TP.jpg"); var fileRef = _workItemClient.UploadAttachment(null, null, "test.jpg", content).Result; // add attachment to the bug item.Relations.Add(new WorkItemRelation() { Url = fileRef.Url, Rel= "AttachedFile", Attributes = new RelationAttributes() { Comment = "this is a weird bug"} }); item = _workItemClient.CreateWorkItem(VSOConfig.projectName, type.ToString(), item).Result; }
/// <summary> /// Create a new Work Item with the given values /// </summary> /// <param name="workItemType">The WorkItem Type (Bug or Task)</param> /// <param name="ex">The exception to report</param> /// <param name="account">Account info for VSTS/TFS</param> /// <param name="message">Optional message to be added to the WorkItem</param> /// <param name="tags">Optional tags (list separated by comma) to be added to the WorkItem</param> /// <returns></returns> public static async Task<BugGuardianResponse> CreateNewWorkItem(WorkItemType workItemType, Exception ex, Account account, string message, IEnumerable<string> tags) { //Pattern: //PATCH https://{account}.visualstudio.com/defaultcollection/{project}/_apis/wit/workitems/${workitemtypename}?api-version={version} //See https://www.visualstudio.com/integrate/api/wit/fields for the fields explanation var createRequestUrl = $"{account.Url}/{account.CollectionName}/{account.ProjectName}/_apis/wit/workitems/${workItemType.ToString()}?{_apiVersion}"; var workItemCreatePATCHData = new List<APIRequest>(); //Title: Exception Name workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = TitleField, Value = ExceptionsHelper.BuildExceptionTitle(ex) }); //Tags workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = TagsField, Value = DefaultTags + (tags != null ? string.Join(";", tags) : String.Empty) }); if (workItemType == WorkItemType.Bug) { //BUG //Repro Steps: Stack Trace workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = ReproStepsField, Value = ExceptionsHelper.BuildExceptionString(ex, message) // Include custom message, if any }); //System Info workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = SystemInfoField, Value = SystemInfoHelper.BuildSystemInfoString() }); } else { //TASK //Description: Stack Trace + System info workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = workItemType == WorkItemType.Bug ? ReproStepsField : DescriptionField, Value = $"{ExceptionsHelper.BuildExceptionString(ex, message)}<br /><hr /><br />{SystemInfoHelper.BuildSystemInfoString()}" // Include custom message, if any }); } //FoundIn: Hash of stack trace workItemCreatePATCHData.Add( new WorkItemCreateRequest() { Operation = WITOperationType.add, Path = FoundInField, Value = ExceptionsHelper.BuildExceptionHash(ex) }); using (var handler = new HttpClientHandler()) { if (!account.IsVSTS) //is TFS, requires NTLM handler.Credentials = new System.Net.NetworkCredential(account.Username, account.Password); using (var client = new HttpClient(handler)) { if (account.IsVSTS) client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Set alternate credentials string credentials = $"{account.Username}:{account.Password}"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Converters.StringToAsciiConverter.StringToAscii(credentials))); try { var responseBody = await HttpOperationsHelper.PatchAsync(client, createRequestUrl, workItemCreatePATCHData); return new BugGuardianResponse() { Success = true, Response = responseBody }; } catch (Exception internalException) { return new BugGuardianResponse() { Success = false, Response = "An error occured. See the Exception.", Exception = internalException }; } } } }
public static WorkItem CreateWorkItem(WorkItemType type) { if (type == WorkItemType.Request) return new RequestWorkItem(); if (type == WorkItemType.Response) return new ResponseWorkItem(); throw new ArgumentException ( "Creation of work item type " + type + " is not currently supported." ); }
/// <summary> /// Check if a WorkItem of the given Type and with the same hash already exists on VSTS/TFS /// </summary> /// <param name="exceptionHash">The MD5 hash of the exception to report</param> /// <param name="workItemType">The WorkItem Type (Bug or Task)</param> /// <param name="account">Account info for VSTS/TFS</param> /// <returns></returns> public static async Task<WorkItemData> GetExistentWorkItemId(string exceptionHash, WorkItemType workItemType, Account account) { //Pattern: //POST https://{account}.visualstudio.com/defaultcollection/_apis/wit/wiql?api-version={version} var wiqlRequestUrl = $"{account.Url}/{account.CollectionName}/_apis/wit/wiql?{_apiVersion}"; var workItemQueryPOSTData = new WorkItemWIQLRequest() { Query = $"Select [System.Id] From WorkItems Where [System.WorkItemType] = '{workItemType.ToString()}' AND [State] <> 'Done' AND [State] <> 'Removed' " + $"AND [System.TeamProject] = '{account.ProjectName}' AND [Microsoft.VSTS.Build.FoundIn] = '{exceptionHash}'" }; using (var handler = new HttpClientHandler()) { if (!account.IsVSTS) //is TFS, requires NTLM handler.Credentials = new System.Net.NetworkCredential(account.Username, account.Password); using (var client = new HttpClient(handler)) { if (account.IsVSTS) client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Set alternate credentials string credentials = $"{account.Username}:{account.Password}"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Converters.StringToAsciiConverter.StringToAscii(credentials))); try { var responseBody = await HttpOperationsHelper.PostAsync(client, wiqlRequestUrl, workItemQueryPOSTData); var responseBodyObj = JsonConvert.DeserializeObject<dynamic>(responseBody); var workItems = (JArray)responseBodyObj.workItems; if (workItems.HasValues) { //Retrieve bug data var id = workItems.First.Value<int>("id"); //Pattern: //GET https://{account}.visualstudio.com/defaultcollection/_apis/wit/WorkItems?id={id}&api-version=1.0 var dataRequestUrl = $"{account.Url}/{account.CollectionName}/_apis/wit/WorkItems?id={id}&{_apiVersion}"; responseBody = await HttpOperationsHelper.GetAsync(client, dataRequestUrl); var workItemData = JsonConvert.DeserializeObject<WorkItemData>(responseBody); //Retrieve bug history //Pattern: //GET https://{account}.visualstudio.com/defaultcollection/_apis/wit/WorkItems/{id}/history var historyRequestUrl = $"{account.Url}/{account.CollectionName}/_apis/wit/WorkItems/{id}/history"; responseBody = await HttpOperationsHelper.GetAsync(client, historyRequestUrl); responseBodyObj = JsonConvert.DeserializeObject<dynamic>(responseBody); var historyItems = (JArray)responseBodyObj.value; if (historyItems.HasValues) workItemData.History = historyItems.ToObject<List<History>>(); return workItemData; } } catch (Exception ex) { int i = 1; } return null; } } }