<WebMethod()>
    Public Function JiraGetActivityTest() As Log()
        Dim ActivityLog As Log() = JiraGetActivity(JiraUserID, 30)
        For Each MyLog In ActivityLog
            Debug.WriteLine(DateTime.Parse(MyLog.Published, Globalization.CultureInfo.InvariantCulture) & " - " & MyLog.Summary & " - " & MyLog.Ticket)
        Next
        Return ActivityLog
    End Function
    Public Structure Log
        Dim Ticket As String
        Dim Published As String
        Dim Summary As String
    End Structure

    <WebMethod()>
    Public Function JiraGetActivity(ByVal UserEID As String, ByVal MaxResults As String) As Log()

        ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        Dim MyLogsToReturn(MaxResults - 1) As Log
        Dim I As Integer = -1
        ' Create a WebRequest to the remote site
        Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://JiraWebServer/activity?maxResults=" & MaxResults & "&streams=user+IS+" & UserEID & "&os_authType=basic&title=mytitle")
        ' NB! Use the following line ONLY if the website is protected
        request.UseDefaultCredentials = True
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
        request.Credentials = CredentialCache.DefaultNetworkCredentials

        request.Credentials = New System.Net.NetworkCredential(Global_asax.GADUsername, Global_asax.GADPassword)
        ' Call the remote site, and parse the data in a response object
        Dim response As System.Net.HttpWebResponse = request.GetResponse()
        ' Check if the response is OK (status code 200)
        If response.StatusCode = System.Net.HttpStatusCode.OK Then
            ' Parse the contents from the response to a stream object
            Dim stream As System.IO.Stream = response.GetResponseStream()
            ' Create a reader for the stream object
            Dim reader As New System.IO.StreamReader(stream)
            ' Read from the stream object using the reader, put the contents in a string
            Dim contents As String = reader.ReadToEnd()
            ' Create a new, empty XML document
            Dim document As New System.Xml.XmlDocument()
            ' Load the contents into the XML document
            document.LoadXml(contents)
            '
            '
            Dim nsmgr As New XmlNamespaceManager(document.NameTable)
            nsmgr.AddNamespace("http://www.w3.org/2005/Atom", document.DocumentElement.NamespaceURI)
            ' Now you have a XmlDocument object that contains the XML from the remote site, you can
            ' use the objects and methods in the System.Xml namespace to read the document
            Dim rssNodes As XmlNodeList = document.SelectNodes("//feed/entry")
            Dim rssContent As StringBuilder = New StringBuilder()

            For Each MyNode As XmlNode In document.ChildNodes
                'Debug.WriteLine(MyNode.se
            Next

            Dim xpathDoc As XPathDocument
            Dim xmlNav As XPathNavigator
            Dim xmlNI As XPathNodeIterator
            Dim XmlReader As XmlReader = New XmlNodeReader(document)
            xpathDoc = New XPathDocument(XmlReader)
            xmlNav = xpathDoc.CreateNavigator()
            xmlNI = xmlNav.Select("/")

            xmlNI.MoveNext()
            xmlNI.Current.MoveToFirstChild()
            If Not (xmlNI.Current.IsEmptyElement) Then
                'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
            End If

            If (xmlNI.Current.HasChildren) Then
                While (xmlNI.Current.Name <> "feed")
                    xmlNI.MoveNext()
                End While

                xmlNI.Current.MoveToFirstChild()

                While (xmlNI.Current.Name <> "entry")
                    xmlNI.Current.MoveToNext()
                    'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                End While

                xmlNI.Current.MoveToFirstChild()

                Dim RestartWhile As Boolean = False

                While True

                    If (Not RestartWhile) Then
                        I += 1
                        While (xmlNI.Current.Name <> "published")
                            If (Not xmlNI.Current.MoveToNext()) Then
                                Return Nothing
                            End If
                            If (xmlNI.Current.Name = "published") Then
                                MyLogsToReturn(I).Published = xmlNI.Current.Value
                                'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                                Exit While
                            End If
                        End While
                    End If

                    RestartWhile = False

                    While (xmlNI.Current.Name <> "activity:target" And xmlNI.Current.Name <> "activity:object")
                        If (Not xmlNI.Current.MoveToNext()) Then
                            Return Nothing
                        End If
                        'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                    End While

                    xmlNI.Current.MoveToFirstChild()

                    While (xmlNI.Current.Name <> "title")
                        If (Not xmlNI.Current.MoveToNext()) Then
                            xmlNI.Current.MoveToParent()
                            xmlNI.Current.MoveToNext()
                            RestartWhile = True
                            Exit While
                        End If
                        If (xmlNI.Current.Value.Contains("IS-")) Then
                            MyLogsToReturn(I).Ticket = xmlNI.Current.Value
                            'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                        End If
                    End While

                    If RestartWhile Then
                        Continue While
                    End If

                    While (xmlNI.Current.Name <> "summary")
                        If (Not xmlNI.Current.MoveToNext()) Then
                            xmlNI.Current.MoveToParent()
                            xmlNI.Current.MoveToNext()
                            RestartWhile = True
                            Exit While
                        End If
                        If (xmlNI.Current.Name = "summary") Then
                            MyLogsToReturn(I).Summary = xmlNI.Current.Value
                            'Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                        End If

                    End While

                    If RestartWhile Then
                        Continue While
                    End If

                    xmlNI.Current.MoveToParent()
                    xmlNI.Current.MoveToParent()
                    If (Not xmlNI.Current.MoveToNext()) Then
                        Exit While
                    End If
                    xmlNI.Current.MoveToFirstChild()

                End While

                Return MyLogsToReturn
            End If
            'Do
            ' Debug.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
            ' Loop While (xmlNI.Current.MoveToPrevious())
        Else
            ' If the call to the remote site fails, you'll have to handle this. There can be many reasons, ie. the 
            ' remote site does not respond (code 404) or your username and password were incorrect (code 401)
            '
            ' See the codes in the System.Net.HttpStatusCode enumerator 
            Throw New Exception("Could not retrieve document from the URL, response code: " & response.StatusCode)
        End If
    End Function

    <WebMethod()>
    Public Function JiraCreateTicketTest() As String
        Return CreateJiraTicket("IS", "TONE-15751", "10000", "Account Issue", "x6588", "TONE-9767", "MyTestSummary", "MyTestDescription", "JiraUserID", "JiraUserID", "System Administrator", "User Incident")
    End Function

    ''' <summary>
    ''' 
    ''' My Function Summary -> https://JiraWebServer/rest/api/latest/issue/IS-383490
    ''' https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/
    ''' https://docs.atlassian.com/software/jira/docs/api/REST/ 
    ''' </summary>
    ''' <param name="Project">IS</param>
    ''' <param name="ToneLocation">TONE-15751</param>
    ''' <param name="TonePriority">10000</param>
    ''' <param name="IssueType">Account Issue</param>
    ''' <param name="CallbackNumber">x6588</param>
    ''' <param name="ToneAffectedObject">TONE-9767</param>
    ''' <param name="Summary">Jira Ticket Title</param>
    ''' <param name="Description">Jira Ticket Description</param>
    ''' <param name="reporter">JiraUserID</param>
    ''' <param name="assignee">JiraUserID</param>
    ''' <param name="ReportedType">User Incident</param>
    ''' <returns></returns>
    <WebMethod(Description:="Creates a Jira ticket")>
    Public Function CreateJiraTicket(ByVal Project As String, ByVal ToneLocation As String, ByVal TonePriority As String, ByVal IssueType As String, ByVal CallbackNumber As String, ByVal ToneAffectedObject As String, ByVal Summary As String, ByVal Description As String, ByVal reporter As String, ByVal assignee As String, ByVal assignmentgroup As String, ByVal ReportedType As String) As String
        'SendJiraRequest("https://JiraWebServer/rest/api/2/issue/", "{""fields"":{""project"":{""key"":""" + Project + """},""customfield_12000"":[{""key"" : """ + AffectedObject + """}],""customfield_12002"":[{""key"" : """ + Location + """}],""customfield_10400"": {""value"": """ + IssueType + """},""reporter"": {""name"": """ & reporter & """},""assignee"": {""name"": """ & assignee & """},""issuetype"":{""name"": """ + ReportedType + """},""summary"":""" & Summary & """,""description"":""" & Description & """,""customfield_10311"":""" + CallbackNumber + """,""priority"":{""id"":""" & Priority & """}}}", "POST")
        Dim DataReturn As String = SendJiraRequest("https://JiraWebServer/rest/api/2/issue/", "{""fields"":{""project"":{""key"":""" + Project + """},""customfield_12000"":[{""key"" : """ + ToneAffectedObject + """}],""customfield_12002"":[{""key"" : """ + ToneLocation + """}],""customfield_10328"":{""value"":""" + assignmentgroup + """},""customfield_10400"": {""value"":""" + IssueType + """},""reporter"": {""name"": """ & reporter & """},""assignee"": {""name"": """ & assignee & """},""issuetype"":{""name"": """ + ReportedType + """},""summary"":""" & Summary & """,""description"":""" & Description & """,""customfield_10311"":""" + CallbackNumber + """,""priority"":{""id"":""" & TonePriority & """}}}", "POST")
        Debug.WriteLine(DataReturn)
        Return DataReturn
    End Function

    <WebMethod(Description:="Searches for a Server Name in Jira")>
    Public Function JiraSearchForServerObject(ByVal Name As String, ByVal Limit As Integer) As String
        Dim DataReturn As String = SendJiraRequest("https://JiraWebServer/rest/insight/1.0/objecttype/21/objects?limit=" & Limit.ToString & "&query=" & Name, Nothing, "GET")
        Debug.WriteLine(DataReturn)
        Return DataReturn
    End Function

    <WebMethod(Description:="Updates a Server Name in Jira")>
    Public Function JiraUpdateServerName(ByVal ServerID As String, ByVal Name As String) As String
        JiraUpdateServerField(ServerID, 171, Name)
    End Function

    <WebMethod(Description:="Updates a Server comment in Jira")>
    Public Function JiraUpdateServerComment(ByVal ServerID As String, ByVal Comment As String) As String
        JiraUpdateServerField(ServerID, 183, Comment)
    End Function

    <WebMethod(Description:="Updates a Server Field in Jira")>
    Public Function JiraUpdateServerField(ByVal ServerID As String, ByVal FieldID As String, ByVal Comment As String) As String
        Dim DataReturn As String = SendJiraRequest("https://JiraWebServer/rest/insight/1.0/object/" & ServerID, "{""attributes"": [{""objectTypeAttributeId"":""" & FieldID & """,""objectAttributeValues"": [{""value"": """ & Comment & """}]}]}", "PUT")
        Debug.WriteLine(DataReturn)
        Return DataReturn
    End Function

    <WebMethod()>
    Public Function JiraSearchForTicket() As String
        Dim sURL As String
        sURL = "https://JiraWebServer/rest/api/2/search?jql="
        sURL &= "project = 'IS'"
        'sURL &= " AND updatedDate >= '2018-12-20' ORDER BY updated ASC"
        sURL &= "&startAt=1"
        sURL &= "&maxResults=5"
        Return SendJiraRequest(sURL, Nothing, "GET")
    End Function
    ' WEB API URL

    Public Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
        Return True
    End Function
    Private Function GetEncodedCredentials() As String
        Dim mergedCredentials As String = String.Format("{0}:{1}", Global_asax.GADUsername, Global_asax.GADPassword)
        Dim byteCredentials As Byte() = UTF8Encoding.UTF8.GetBytes(mergedCredentials)
        Return Convert.ToBase64String(byteCredentials)
    End Function

    Private Function SendJiraRequest(ByVal Request As String, ByVal Body As String, Optional method As String = "GET") As String

        ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        sURL = Request

        ' Create Web Request
        Dim objWebRequest As WebRequest
        objWebRequest = WebRequest.Create(sURL)

        ' Basic Authentication on Remote Web Site
        objWebRequest.Headers.Add("Authorization: Basic " & GetEncodedCredentials())

        objWebRequest.Method = method

        If Body IsNot Nothing Then
            objWebRequest.ContentType = "application/json"
            Dim data = Encoding.UTF8.GetBytes(Body)
            objWebRequest.ContentLength = data.Length
            Using requestStream = objWebRequest.GetRequestStream
                requestStream.Write(data, 0, data.Length)
                requestStream.Close()

                Using responseStream = objWebRequest.GetResponse.GetResponseStream
                    Using reader As New StreamReader(responseStream)
                        Return reader.ReadToEnd()
                    End Using
                End Using
            End Using
        Else
            ' Get Response
            Dim objStream As Stream
            Try
                objStream = objWebRequest.GetResponse.GetResponseStream()


                ' Display API Query Results
                Dim i As Integer = 0
                Dim sLine As String = ""
                Dim objStreamReader As New StreamReader(objStream)

                Dim StringToReturn As String = objStreamReader.ReadToEnd()
                Return StringToReturn

                Do While Not sLine Is Nothing
                    i += 1
                    sLine = objStreamReader.ReadLine
                    If Not sLine Is Nothing Then
                        Debug.WriteLine("Line {0}: {1}", i, sLine)
                    End If
                Loop


            Catch ex As Exception
                Console.Write(ex.ToString())
                Return Nothing
            End Try
        End If

        Return Nothing
    End Function

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax