Пример #1
0
        public async Task <TicketsResult> CreateTicket(string title, string description, UrgencyLevel urgency)
        {
            try
            {
                var request = ServiceNowRestClientHelper.CreateRequest(TicketResource, token);
                var body    = new CreateTicketRequest()
                {
                    caller_id         = userId,
                    short_description = title,
                    description       = description,
                    urgency           = ServiceNowRestClientHelper.UrgencyToString[urgency]
                };
                request.AddJsonBody(body);
                var response = await client.ExecuteTaskAsync(request, CancellationToken.None, Method.POST);

                // Return Response
                return(response.ProcessCreateUpdateCloseTicketIRestResponse());
            }
            catch (Exception ex)
            {
                return(new TicketsResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #2
0
        public async Task <KnowledgesResult> CountKnowledge(string query)
        {
            try
            {
                var request = ServiceNowRestClientHelper.CreateRequest(KnowledgeCount, token);

                var sysparmQuery = await CreateKnowledgeSearchQuery(query : query);

                request.AddParameter("sysparm_query", string.Join('^', sysparmQuery));

                request.AddParameter("sysparm_count", true);

                var result = await client.GetAsync <SingleAggregateResponse>(request);

                return(new KnowledgesResult()
                {
                    Success = true,
                    Knowledges = new Knowledge[result.result.stats.count]
                });
            }
            catch (Exception ex)
            {
                return(new KnowledgesResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #3
0
        public async Task <TicketsResult> CloseTicket(string id, string reason)
        {
            try
            {
                // minimum field required: https://community.servicenow.com/community?id=community_question&sys_id=84ceb6a5db58dbc01dcaf3231f9619e9
                var request = ServiceNowRestClientHelper.CreateRequest($"{TicketResource}/{id}?sysparm_exclude_ref_link=true", token);
                var body    = new
                {
                    close_code  = "Closed/Resolved by Caller",
                    state       = "7",
                    caller_id   = userId,
                    close_notes = reason
                };
                request.JsonSerializer = new JsonNoNull();
                request.AddJsonBody(body);

                var response = await client.ExecuteTaskAsync(request, CancellationToken.None, Method.PATCH);

                // Process and Return Correct Response
                return(response.ProcessCreateUpdateCloseTicketIRestResponse());
            }
            catch (Exception ex)
            {
                return(new TicketsResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #4
0
        public async Task <KnowledgesResult> SearchKnowledge(string query, int pageIndex)
        {
            try
            {
                var request = ServiceNowRestClientHelper.CreateRequest(KnowledgeResource, token);

                var sysparmQuery = await CreateKnowledgeSearchQuery(query : query);

                request.AddParameter("sysparm_query", string.Join('^', sysparmQuery));

                request.AddParameter("sysparm_limit", limitSize);

                request.AddParameter("sysparm_offset", limitSize * pageIndex);

                var result = await client.GetAsync <MultiKnowledgesResponse>(request);

                return(new KnowledgesResult()
                {
                    Success = true,
                    Knowledges = result.result?.Select(r => ConvertKnowledge(r)).ToArray()
                });
            }
            catch (Exception ex)
            {
                return(new KnowledgesResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #5
0
        public async Task <TicketsResult> UpdateTicket(string id, string title = null, string description = null, UrgencyLevel urgency = UrgencyLevel.None)
        {
            var request = ServiceNowRestClientHelper.CreateRequest($"{TicketResource}/{id}?sysparm_exclude_ref_link=true", token);
            var body    = new CreateTicketRequest()
            {
                short_description = title,
                description       = description,
                urgency           = urgency == UrgencyLevel.None ? null : ServiceNowRestClientHelper.UrgencyToString[urgency]
            };

            request.JsonSerializer = new JsonNoNull();
            request.AddJsonBody(body);
            try
            {
                var response = await client.ExecuteTaskAsync(request, CancellationToken.None, Method.PATCH);

                // Process and Return Correct Response
                return(response.ProcessCreateUpdateCloseTicketIRestResponse());
            }
            catch (Exception ex)
            {
                return(new TicketsResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #6
0
        public async Task <TicketsResult> CountTicket(string query = null, List <UrgencyLevel> urgencies = null, string id = null, List <TicketState> states = null, string number = null)
        {
            try
            {
                var request = ServiceNowRestClientHelper.CreateRequest(TicketCount, token);

                var sysparmQuery = await CreateTicketSearchQuery(query : query, urgencies : urgencies, id : id, states : states, number : number);

                request.AddParameter("sysparm_query", string.Join('^', sysparmQuery));

                request.AddParameter("sysparm_count", true);

                var response = await client.ExecuteTaskAsync(request, CancellationToken.None, Method.GET);

                // Process and Return Correct Response
                return(response.ProcessCountTicketIRestResponse());
            }
            catch (Exception ex)
            {
                return(new TicketsResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #7
0
        public async Task <TicketsResult> SearchTicket(int pageIndex, string query = null, List <UrgencyLevel> urgencies = null, string id = null, List <TicketState> states = null, string number = null)
        {
            try
            {
                var request = ServiceNowRestClientHelper.CreateRequest(TicketResource, token);

                var sysparmQuery = await CreateTicketSearchQuery(query : query, urgencies : urgencies, id : id, states : states, number : number);

                request.AddParameter("sysparm_query", string.Join('^', sysparmQuery));

                request.AddParameter("sysparm_limit", limitSize);

                request.AddParameter("sysparm_offset", limitSize * pageIndex);

                var result = await client.GetAsync <MultiTicketsResponse>(request);

                return(new TicketsResult()
                {
                    Success = true,
                    Tickets = result.result?.Select(r => ConvertTicket(r)).ToArray()
                });
            }
            catch (Exception ex)
            {
                return(new TicketsResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Пример #8
0
        // Calls ServiceNow Scripted REST API to programmatically create new rest messages
        public async Task <HttpStatusCode> CreateSubscriptionBusinessRule(string filterCondition, string filterName, string notificationNameSpace = null, string postNotificationAPIName = null)
        {
            try
            {
                // TODO: build filterCondition from userinput instead of hardcoding
                var url     = this.baseUrl + $"/createnewbusinessrule?name={filterName}&whenToRun=after&tableName=incident&action=action_insert&filterCondition=urgencyVALCHANGES^ORdescriptionVALCHANGES^ORpriorityVALCHANGES^ORdescriptionVALCHANGES^ORassigned_toVALCHANGES^EQ&advance=true";
                var request = ServiceNowRestClientHelper.CreateRequest(url, "Bearer " + token);
                notificationNameSpace   = "'" + notificationNameSpace + "'";
                postNotificationAPIName = "'" + postNotificationAPIName + "'";

                // Create BusinessRule to execute when
                var postBusinessRule = new Dictionary <string, string>();
                postBusinessRule["script"] = "(function executeRule(current, previous /*null when async*/) {var strBody = \"{\"; strBody += \"'BusinessRuleName': '" + filterName + "', \"; strBody += \"'Id': '\" + current.number.toString() + \"', \"; strBody += \"'Title': '\" + current.short_description.toString() + \"', \"; strBody += \"'Description': '\" + current.description.toString() + \"', \"; strBody += \"'Category': '\" + current.category.toString() + \"', \"; strBody += \"'Impact': '\" + current.impact.toString() + \"',\"; strBody += \"'Urgency': '\" + current.urgency.toString() + \"'\"; strBody += \"}\"; var request = new sn_ws.RESTMessageV2(" + notificationNameSpace + ", " + postNotificationAPIName + "); request.setRequestBody(JSON.stringify(strBody)); var response = request.execute(); var responseBody = response.getBody(); var httpStatus = response.getStatusCode();})(current, previous);";

                // Send Request to ServiceNow
                request.AddJsonBody(postBusinessRule);

                // Post BusinessRule
                var response = await client.PostAsync <Dictionary <string, string> >(request);

                var val = response["result"];

                return(val.ToLower().Contains("successfully") ? HttpStatusCode.OK : HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #9
0
        private async Task <string> GetUserId()
        {
            var request = ServiceNowRestClientHelper.CreateRequest(getUserIdResource, token);
            var userId  = await client.GetAsync <GetUserIdResponse>(request);

            if (userId == null || string.IsNullOrEmpty(userId.result))
            {
                throw new Exception(SharedStrings.InvalidGetUserId);
            }

            return(userId.result);
        }
Пример #10
0
        // Calls ServiceNow Scripted REST API to programmatically create business rules
        public async Task <HttpStatusCode> CreateNewRestMessage(string callBackName, string postName)
        {
            try
            {
                var url = this.baseUrl + $"/createnewrestmessage?name={callBackName}&postFunctionName={postName}";

                var request = ServiceNowRestClientHelper.CreateRequest(url, "Bearer " + token);

                // Post RestMessage
                var postBusinessRule = new Dictionary <string, string>();
                postBusinessRule["endPtName"] = this.callBackUrl + "/api/servicenow/incidents";

                request.AddJsonBody(postBusinessRule);
                var response = await client.PostAsync <Dictionary <string, string> >(request);

                var val = response["result"];
                return(val.ToLower().Contains("successfully") ? HttpStatusCode.OK : HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }