Exemple #1
0
        public TFSBug CreateBug(SNDevelopmentItem developmentItem, string teamProject)
        {
            TFSBug tfsBug = null;
            // Construct the object containing field values required for the new work item
            JsonPatchDocument patchDocument = new JsonPatchDocument();

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Title",
                Value     = developmentItem.Short_Description == null ? "No description in ServiceNow" : developmentItem.Short_Description
            });
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/FET.SNDefect",
                Value     = developmentItem.Number
            }
                );
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/FET.SNInternalId",
                Value     = developmentItem.SystemId
            }
                );


            string serverUrl = (string)configReader.GetValue("TFSServerUrl", typeof(string));
            //Initialise the connection to the TFS server
            VssConnection connection = new VssConnection(new Uri(serverUrl), new VssCredentials(new WindowsCredential(true)));

            using (WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>())
            {
                // Get the project to create the work item in
                TeamProjectReference projectReference = FindProject(connection, teamProject);

                if (projectReference != null)
                {
                    // Create the new work item
                    WorkItem newWorkItem = workItemTrackingClient.CreateWorkItemAsync(patchDocument, projectReference.Id, "Bug").Result;

                    if (newWorkItem != null)
                    {
                        tfsBug = GetBugFromSNDevItem(developmentItem);
                    }
                }
            }
            return(tfsBug);
        }
        private bool UpdateEnhancement(TFSProductBacklogItem backlogItem)
        {
            bool retValue             = false;
            SNDevelopmentItem devItem = new SNDevelopmentItem()
            {
                Number   = backlogItem.ServiceNowEnhancement,
                SystemId = backlogItem.ServiceNowInternalId,
                External_Reference_Id = string.Format("PBI{0}", backlogItem.ID),
                Short_Description     = backlogItem.Title
            };

            try
            {
                var    devItem2          = snClient.GetEnhancement(devItem.SystemId);
                string snState           = Settings.Instance.TfsWIStateMapping.GetValueOrDefault(backlogItem.State);
                string snAssignmentGroup = devItem2.Assignment_Group;
                string assignmentGroup   = Settings.Instance.TfsWIStateAssignmentGroup.GetValueOrDefault(backlogItem.State);
                if (!string.IsNullOrEmpty(snState))
                {
                    // Do not modify SN state if TFS state order is lower than ServiceNow state order
                    int tfsStateOrder = Settings.Instance.TfsStateOrder.GetValueOrDefault(backlogItem.State, 0);
                    int snStateOrder  = Settings.Instance.SnEnhancementStateOrder.GetValueOrDefault(devItem2.State, 0);
                    if (snStateOrder <= tfsStateOrder)
                    {
                        devItem.State = snState;
                    }

                    // Only modify the assignment group if the state is "Work in Progress"
                    if (!string.IsNullOrEmpty(assignmentGroup) && (snState == "Work in Progress"))
                    {
                        if ((snAssignmentGroup == "Navision Development") || (snAssignmentGroup == "Navision Support"))
                        {
                            devItem.Assignment_Group = assignmentGroup;
                        }
                    }
                    if ((devItem.State != devItem2.State) ||
                        (devItem.Assignment_Group != devItem2.Assignment_Group) ||
                        (devItem.External_Reference_Id != devItem2.External_Reference_Id))
                    {
                        retValue = snClient.UpdateEnhancement(devItem);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return(retValue);
        }
Exemple #3
0
        public TFSBug UpdateBug(SNDevelopmentItem developmentItem, TFSBug tFSBug)
        {
            // Construct the object containing field values required for the new work item
            JsonPatchDocument patchDocument = new JsonPatchDocument();

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Title",
                Value     = developmentItem.Short_Description == null ? "No description in ServiceNow" : developmentItem.Short_Description
            });
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.State",
                Value     = tFSBug.State
            }
                );

            string serverUrl = (string)configReader.GetValue("TFSServerUrl", typeof(string));
            //Initialise the connection to the TFS server
            VssConnection connection = new VssConnection(new Uri(serverUrl), new VssCredentials(new WindowsCredential(true)));

            using (WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>())
            {
                // Create the new work item
                WorkItem UpdatedWorkItem = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, tFSBug.ID).Result;
                if (UpdatedWorkItem != null)
                {
                    tFSBug = GetBugFromSNDevItem(developmentItem);
                }
            }
            return(tFSBug);
        }
 public bool UpdateDefect(SNDevelopmentItem devItem)
 {
     return(UpdateServiceNowEntityAsync <Defect>(devItem).Result);
 }
        public SNDevelopmentItem GetDefect(string systemId)
        {
            SNDevelopmentItem devItem = GetServiceNowEntityAsync <Defect>(systemId).Result;

            return(devItem);
        }
 public bool UpdateEnhancement(SNDevelopmentItem devItem)
 {
     return(UpdateServiceNowEntityAsync <Enhancement>(devItem).Result);
 }
        private async Task <bool> UpdateServiceNowEntityAsync <T>(SNDevelopmentItem devItem) where T : SNCommon
        {
            bool     retValue    = false;
            string   snTableName = "";
            SNCommon snRecord    = new SNCommon()
            {
                Short_Description = devItem.Short_Description,
                State             = devItem.State,
                Correlation_Id    = devItem.External_Reference_Id,
                Assignment_Group  = string.IsNullOrEmpty(devItem.Assignment_Group) ?  null : new SNLookup()
                {
                    Display_Value = devItem.Assignment_Group
                }
            };

            if (typeof(T) == typeof(Enhancement))
            {
                snTableName = "rm_enhancement";
            }
            if (typeof(T) == typeof(Defect))
            {
                snTableName = "rm_defect";
            }
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    string targetBaseUrl = (string)configReader.GetValue("ServiceNowBaseUrl", typeof(string));
                    string authUserName  = (string)configReader.GetValue("ServiceNowUser", typeof(string));
                    string authPassword  = (string)configReader.GetValue("ServiceNowPassword", typeof(string));

                    httpClient.BaseAddress = new Uri(targetBaseUrl);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    //Http authententification
                    var authToken = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", authUserName, authPassword));

                    //Build the request message
                    string jsonContent = JsonConvert.SerializeObject(snRecord, Formatting.None,
                                                                     new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver  = new LowerCasePropertyNamesContractResolver(),
                        Converters        = { new FormatSNLookupAsTextConverter() }
                    });
                    HttpRequestMessage requestMessage = new HttpRequestMessage();
                    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    requestMessage.RequestUri = new Uri(string.Format(@"{0}/table/{1}/{2}?sysparm_display_value=true&sysparm_input_display_value=true&sysparm_view=NAV", targetBaseUrl, snTableName, devItem.SystemId));
                    requestMessage.Content    = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    var testContent = requestMessage.ToString();
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
                    requestMessage.Method = HttpMethod.Put;
                    HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        retValue = true;
                    }
                    else
                    {
                        logger.Error(string.Format(@"Could not update {0}: {1}", devItem.Number, responseMessage.ReasonPhrase));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return(retValue);
        }
        private async Task <SNDevelopmentItem> GetServiceNowEntityAsync <T>(string systemId) where T : SNCommon
        {
            SNDevelopmentItem snEntity    = null;
            string            snTableName = "";

            if (typeof(T) == typeof(Enhancement))
            {
                snTableName = "rm_enhancement";
            }
            if (typeof(T) == typeof(Defect))
            {
                snTableName = "rm_defect";
            }
            try
            {
                using (var httpClient = new HttpClient())
                {
                    string targetBaseUrl = (string)configReader.GetValue("ServiceNowBaseUrl", typeof(string));
                    string authUserName  = (string)configReader.GetValue("ServiceNowUser", typeof(string));
                    string authPassword  = (string)configReader.GetValue("ServiceNowPassword", typeof(string));

                    httpClient.BaseAddress = new Uri(targetBaseUrl);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    //Http authententification
                    var authToken = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", authUserName, authPassword));

                    //Build the request message
                    HttpRequestMessage requestMessage = new HttpRequestMessage();
                    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    requestMessage.RequestUri            = new Uri(string.Format(@"{0}/table/{1}/{2}?sysparm_display_value=true&sysparm_view=NAV", targetBaseUrl, snTableName, systemId));
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
                    requestMessage.Method = HttpMethod.Get;
                    HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        string responseText = await responseMessage.Content.ReadAsStringAsync();

                        responseText = responseText.Replace("u_fet_company2.u_product_line", "product_line").Replace("u_fet_company2.u_segment", "segment");

                        // Deserialize Json response into an enhancement
                        JObject snQueryResult = JObject.Parse(responseText);
                        var     enhancement   = snQueryResult["result"].ToObject <T>();
                        if (enhancement != null)
                        {
                            snEntity = new SNDevelopmentItem()
                            {
                                SystemId          = enhancement.Sys_Id,
                                Number            = enhancement.Number,
                                Assigned_To       = enhancement.Assignment_Group != null ? enhancement.Assignment_Group.Display_Value : "",
                                State             = enhancement.State,
                                Short_Description = enhancement.Short_Description
                            };
                        }
                    }
                    else
                    {
                        logger.Error(string.Format(@"The response from ServiceNow is: {0}", responseMessage.ReasonPhrase));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return(snEntity);
        }
        public TFSBug InsertOrUpdateSingleBug(SNDevelopmentItem developmentItem)
        {
            TFSBug tfsBug    = null;
            TFSBug curtfsBug = tfsClient.GetBugFromSNDevItem(developmentItem);

            try
            {
                if (curtfsBug != null)
                {
                    //Update Bug in TFS
                    try
                    {
                        tfsBug = curtfsBug;
                        string tfsState = Settings.Instance.SnDefectStateMapping.GetValueOrDefault(developmentItem.State);
                        if (!string.IsNullOrEmpty(tfsState))
                        {
                            int tfsStateOrder = Settings.Instance.TfsStateOrder.GetValueOrDefault(tfsState, 0);
                            int snStateOrder  = Settings.Instance.SnEnhancementStateOrder.GetValueOrDefault(developmentItem.State, 0);
                            if (snStateOrder > tfsStateOrder)
                            {
                                tfsBug.State = tfsState;
                            }
                        }
                        if (curtfsBug.Title != developmentItem.Short_Description)
                        {
                            tfsBug.Title = developmentItem.Short_Description;
                        }
                        if ((tfsBug.Title != curtfsBug.Title) || (tfsBug.State != curtfsBug.State))
                        {
                            tfsClient.UpdateBug(developmentItem, tfsBug);
                            nbBugUpdated++;
                            tfsBug = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
                else
                {
                    //Create Bug in TFS
                    try
                    {
                        // The project come from the mapping between Assignment Group and team project in Settings file
                        string assginmentGroup = developmentItem.Assignment_Group == null ? string.Empty : developmentItem.Assignment_Group;
                        string teamProject     = Settings.Instance.SnAssignGroupMapping.GetValueOrDefault(assginmentGroup);
                        string tfsState        = Settings.Instance.SnDefectStateMapping.GetValueOrDefault(developmentItem.State);
                        if ((tfsState == "New") && (!string.IsNullOrEmpty(teamProject)))
                        {
                            tfsBug = tfsClient.CreateBug(developmentItem, teamProject);
                            nbBugCreated++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(tfsBug);
        }
        private TFSProductBacklogItem InsertOrUpdateSinglePBI(SNDevelopmentItem developmentItem)
        {
            TFSProductBacklogItem curtfsPBI = tfsClient.GetPBIFromSNDevItem(developmentItem);
            TFSProductBacklogItem tfsPBI    = null;

            try
            {
                if (curtfsPBI != null)
                {
                    //Update PBI in TFS
                    try
                    {
                        tfsPBI = curtfsPBI;
                        string tfsState = Settings.Instance.SnEnhancementStateMapping.GetValueOrDefault(developmentItem.State);
                        if (!string.IsNullOrEmpty(tfsState))
                        {
                            int tfsStateOrder = Settings.Instance.TfsStateOrder.GetValueOrDefault(tfsState, 0);
                            int snStateOrder  = Settings.Instance.SnEnhancementStateOrder.GetValueOrDefault(developmentItem.State, 0);
                            if (snStateOrder > tfsStateOrder)
                            {
                                tfsPBI.State = tfsState;
                            }
                        }
                        if (curtfsPBI.Title != developmentItem.Short_Description)
                        {
                            tfsPBI.Title = developmentItem.Short_Description;
                        }
                        if ((tfsPBI.Title != curtfsPBI.Title) || (tfsPBI.State != curtfsPBI.State))
                        {
                            tfsClient.UpdateProductBacklogItem(developmentItem, tfsPBI);
                            nbPBIUpdated++;
                            tfsPBI = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
                else
                {
                    //Create PBI in TFS
                    try
                    {
                        // The project come from the mapping between Assignment Group and team project in Settings file
                        string assginmentGroup = developmentItem.Assignment_Group == null?string.Empty: developmentItem.Assignment_Group;
                        string teamProject     = Settings.Instance.SnAssignGroupMapping.GetValueOrDefault(assginmentGroup);
                        string tfsState        = Settings.Instance.SnEnhancementStateMapping.GetValueOrDefault(developmentItem.State);
                        if ((tfsState == "New") && (!string.IsNullOrEmpty(teamProject)))
                        {
                            tfsPBI = tfsClient.CreateProductBacklogItem(developmentItem, teamProject);
                            nbPBICreated++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(tfsPBI);
        }
Exemple #11
0
        public TFSProductBacklogItem GetPBIFromSNDevItem(SNDevelopmentItem developmentItem)
        {
            TFSProductBacklogItem tfsPBI = null;

            try
            {
                //create a wiql object and build our query
                Wiql wiql = new Wiql()
                {
                    Query = "Select [ID],[Title],[ServiceNow InternalId] " +
                            "From WorkItems " +
                            "Where [Work Item Type] = 'Product Backlog Item' " +
                            "And [ServiceNow InternalId] = '" + developmentItem.SystemId + "' "
                };

                string serverUrl = (string)configReader.GetValue("TFSServerUrl", typeof(string));
                //Initialise the connection to the TFS server
                VssConnection connection = new VssConnection(new Uri(serverUrl), new VssCredentials(new WindowsCredential(true)));

                //create instance of work item tracking http client
                using (WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>())
                {
                    //execute the query to get the list of work items in teh results
                    WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                    //Some error handling
                    if (workItemQueryResult.WorkItems.Count() != 0)
                    {
                        //need to get the work item Id for the GET request
                        int wiID = workItemQueryResult.WorkItems.First().Id;


                        //build a list of the fields we want to see
                        string[] fields = new string[5];
                        fields[0] = "System.Id";
                        fields[1] = "System.Title";
                        fields[2] = "System.State";
                        fields[3] = "FET.SNEnhancement";
                        fields[4] = "FET.SNInternalId";

                        var workItem = workItemTrackingHttpClient.GetWorkItemAsync(wiID, fields, workItemQueryResult.AsOf).Result;

                        if (workItem != null)
                        {
                            tfsPBI = new TFSProductBacklogItem()
                            {
                                ID    = workItem.Id.Value,
                                Title = (string)workItem.Fields[fields[1]],
                                State = (string)workItem.Fields[fields[2]],
                                ServiceNowEnhancement = (string)workItem.Fields[fields[3]],
                                ServiceNowInternalId  = (string)workItem.Fields[fields[4]]
                            };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(tfsPBI);
        }