Guest User

Untitled

a guest
Dec 16th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.54 KB | None | 0 0
  1. Public Class FreshserviceAPI
  2. Implements IFreshserviceAPI
  3.  
  4.  
  5. Public Sub New(portalURL As String, username As String, password As String)
  6. Me.PortalURL = portalURL
  7. Me.UserName = username
  8. Me.Password = password
  9. End Sub
  10.  
  11. Public Property PortalURL As String = "" Implements IFreshserviceAPI.PortalURL
  12. Public Property UserName As String = "" Implements IFreshserviceAPI.UserName
  13. Public Property Password As String = "" Implements IFreshserviceAPI.Password
  14.  
  15.  
  16. Public Function GetTicket(id As Long) As HelpdeskTicket Implements IFreshserviceAPI.GetTicket
  17.  
  18. Dim ticket As HelpdeskTicket = Nothing
  19.  
  20. Dim ticketResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/helpdesk/tickets/{id}.json"
  21. Dim response As HttpWebResponse = HttpUtil.SubmitHttpRequest(ticketResourceURL,
  22. method:=HttpMethod.Get,
  23. basicAuthUser:=Me.UserName,
  24. basicAuthPassword:=Me.Password)
  25. If response IsNot Nothing Then
  26. ticket = GetItemFromResponse(response, Function(root As TicketResponseRoot)
  27. Return root.helpdesk_ticket
  28. End Function)
  29. End If
  30.  
  31. Return ticket
  32.  
  33. End Function
  34.  
  35. Public Function CreateTicket(ticket As HelpdeskTicket) As HelpdeskTicket Implements IFreshserviceAPI.CreateTicket
  36.  
  37. Dim createdTicket As HelpdeskTicket = Nothing
  38.  
  39. Dim ticketResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/helpdesk/tickets.json"
  40. Dim response As HttpWebResponse = HttpUtil.SubmitHttpRequest(ticketResourceURL,
  41. method:=HttpMethod.Post,
  42. basicAuthUser:=Me.UserName,
  43. basicAuthPassword:=Me.Password,
  44. requestBodyContent:=ticket.ToPostJson)
  45.  
  46. If response IsNot Nothing Then
  47. createdTicket = GetItemFromResponse(response, Function(root As TicketPostResponseRoot)
  48. Return root.item.helpdesk_ticket
  49. End Function)
  50. End If
  51.  
  52. Return createdTicket
  53.  
  54. End Function
  55.  
  56. Public Function UpdateTicket(ticket As HelpdeskTicket, id As Long) As HelpdeskTicket Implements IFreshserviceAPI.UpdateTicket
  57.  
  58. Dim updatedTicket As HelpdeskTicket = Nothing
  59.  
  60. Dim ticketResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/helpdesk/tickets/{id}.json"
  61. Dim response As HttpWebResponse = HttpUtil.SubmitHttpRequest(ticketResourceURL,
  62. method:=HttpMethod.Put,
  63. basicAuthUser:=Me.UserName,
  64. basicAuthPassword:=Me.Password,
  65. requestBodyContent:=ticket.ToPostJson)
  66.  
  67.  
  68.  
  69. If response IsNot Nothing Then
  70. updatedTicket = GetItemFromResponse(response, Function(root As TicketPutttResponseRoot)
  71. Return root.ticket
  72. End Function)
  73. End If
  74.  
  75.  
  76.  
  77. Return updatedTicket
  78.  
  79. End Function
  80.  
  81. Public Function GetNote(id As Long) As Note Implements IFreshserviceAPI.GetNote
  82.  
  83. Throw New NotImplementedException()
  84.  
  85. End Function
  86.  
  87. Public Function CreateNote(note As Note, ticketID As Long) As Note Implements IFreshserviceAPI.CreateNote
  88.  
  89. Dim createdNote As Note = Nothing
  90.  
  91. Dim noteResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/helpdesk/tickets/{ticketID}/conversations/note.json"
  92. Dim response As HttpWebResponse = HttpUtil.SubmitHttpRequest(noteResourceURL,
  93. method:=HttpMethod.Post,
  94. basicAuthUser:=Me.UserName,
  95. basicAuthPassword:=Me.Password,
  96. requestBodyContent:=note.ToPostJson())
  97. If response IsNot Nothing Then
  98. createdNote = GetItemFromResponse(response, Function(root As NoteResponseRoot)
  99. Return root.note
  100. End Function)
  101. End If
  102.  
  103. Return createdNote
  104.  
  105. End Function
  106.  
  107.  
  108. Public Function CreateNoteWithAttachment(noteBody As String, attachment As Attachment, ticketID As Long) As Attachment Implements IFreshserviceAPI.CreateNoteWithAttachment
  109.  
  110. Dim createdAttachment As Attachment = Nothing
  111.  
  112. Dim responseJson As String = ""
  113.  
  114. Using client = New HttpClient()
  115. Dim basicAuthCreds As String = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(UserName & ":" & Password))
  116. client.DefaultRequestHeaders.Authorization = New Headers.AuthenticationHeaderValue("Basic", basicAuthCreds)
  117. Using formData = New MultipartFormDataContent()
  118.  
  119. formData.Add(New StringContent(noteBody), name:="helpdesk_note[body]")
  120.  
  121. formData.Add(New ByteArrayContent(attachment.file_data),
  122. name:="helpdesk_note[attachments][][resource]",
  123. fileName:=attachment.content_file_name)
  124.  
  125. Dim noteResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/helpdesk/tickets/{ticketID}/conversations/note.json"
  126. HttpUtil.SetSslProtocal()
  127. Dim response = client.PostAsync(noteResourceURL, formData).Result
  128. If response.IsSuccessStatusCode Then
  129. Using streamReader As New StreamReader(response.Content.ReadAsStreamAsync().Result)
  130. responseJson = streamReader.ReadToEnd()
  131. End Using
  132. End If
  133. End Using
  134. End Using
  135.  
  136. If Not String.IsNullOrWhiteSpace(responseJson) Then
  137. Dim noteRoot = JsonConvert.DeserializeObject(Of NoteResponseRoot)(responseJson)
  138. If noteRoot IsNot Nothing Then
  139. Dim createdNote As Note = noteRoot.note
  140. If createdNote IsNot Nothing Then
  141. If createdNote.attachments?.Any() Then
  142. attachment = createdNote.attachments.First()
  143. End If
  144. End If
  145. End If
  146. End If
  147.  
  148. Return attachment
  149.  
  150. End Function
  151.  
  152.  
  153. Public Function FindAgentUser(emailAddress As String) As User Implements IFreshserviceAPI.FindAgentUser
  154.  
  155. Dim user As User = Nothing
  156.  
  157.  
  158. If String.IsNullOrWhiteSpace(emailAddress) Then
  159. '//Fresh will pull ALL agents if you pass a blank email address
  160. '//we don't want that.
  161. Return Nothing
  162. End If
  163.  
  164. Dim usersResourceURL As String = $"{Me.PortalURL.TrimEnd("/"c)}/agents.json?query={WebUtility.UrlEncode("email is " & emailAddress)}"
  165. Dim response As HttpWebResponse = HttpUtil.SubmitHttpRequest(usersResourceURL,
  166. basicAuthUser:=Me.UserName,
  167. basicAuthPassword:=Me.Password,
  168. method:=HttpMethod.Get)
  169. If response IsNot Nothing Then
  170.  
  171. user = GetItemFromResponse(response, Function(agentItems As List(Of AgentListItem))
  172. If agentItems?.Any() Then
  173. Dim agent = agentItems.First()
  174. If agent IsNot Nothing Then
  175. Return If(agent Is Nothing, Nothing, agent.agent.user)
  176. End If
  177. End If
  178. Return Nothing
  179. End Function)
  180.  
  181. End If
  182.  
  183.  
  184. Return user
  185.  
  186. End Function
  187.  
  188.  
  189.  
  190.  
  191. Private Function GetItemFromResponse(Of ItemType, ItemRootType)(response As HttpWebResponse,
  192. itemExtractor As Func(Of ItemRootType, ItemType)) As ItemType
  193.  
  194. Dim item As ItemType = Nothing
  195.  
  196. Dim responseBodyJSON As String = ""
  197. Using streamReader As New StreamReader(response.GetResponseStream())
  198. responseBodyJSON = streamReader.ReadToEnd()
  199. Dim jsonRoot As ItemRootType = JsonConvert.DeserializeObject(Of ItemRootType)(responseBodyJSON)
  200. item = itemExtractor(jsonRoot)
  201. End Using
  202.  
  203. Return item
  204.  
  205. End Function
  206.  
  207. Public Class HelpdeskTicket
  208.  
  209.  
  210. <JsonProperty("email")>
  211. Public Property RequesterEmail As String
  212.  
  213. Public Property category As Object
  214.  
  215. Public Property cc_email As CcEmail
  216.  
  217. <JsonConverter(GetType(IsoDateTimeConverter))>
  218. Public Property created_at As DateTime?
  219.  
  220. Public Property deleted As Boolean?
  221.  
  222. Public Property department_id_value As Object
  223.  
  224. Public Property display_id As Integer?
  225.  
  226. <JsonConverter(GetType(IsoDateTimeConverter))>
  227. Public Property due_by As DateTime?
  228.  
  229. Public Property email_config_id As Object
  230.  
  231. <JsonConverter(GetType(IsoDateTimeConverter))>
  232. Public Property frDueBy As DateTime?
  233.  
  234. Public Property fr_escalated As Boolean?
  235.  
  236. Public Property group_id As Object
  237.  
  238. Public Property id As Long?
  239.  
  240. Public Property impact As Integer?
  241.  
  242. Public Property isescalated As Boolean?
  243.  
  244. Public Property item_category As Object
  245.  
  246. Public Property notes As List(Of NoteResponseRoot)
  247.  
  248. Public Property owner_id As Object
  249.  
  250. Public Property priority As Integer?
  251.  
  252. Public Property requester_id As Long?
  253.  
  254. Public Property responder_id As Object
  255.  
  256. Public Property source As Integer?
  257.  
  258. Public Property spam As Boolean?
  259.  
  260. Public Property status As Integer?
  261.  
  262. Public Property sub_category As Object
  263.  
  264. Public Property subject As String
  265.  
  266. Public Property ticket_type As String
  267.  
  268. Public Property to_email As Object
  269.  
  270. <JsonConverter(GetType(IsoDateTimeConverter))>
  271. Public Property updated_at As DateTime?
  272.  
  273. Public Property urgency As Integer?
  274.  
  275. Public Property description As String
  276.  
  277. Public Property description_html As String
  278.  
  279. Public Property status_name As String
  280.  
  281. Public Property requester_status_name As String
  282.  
  283. Public Property priority_name As String
  284.  
  285. Public Property source_name As String
  286.  
  287. Public Property requester_name As String
  288.  
  289. Public Property responder_name As String
  290.  
  291. Public Property to_emails As Object
  292.  
  293. Public Property department_name As Object
  294.  
  295. Public Property assoc_problem_id As Object
  296.  
  297. Public Property assoc_change_id As Object
  298.  
  299. Public Property assoc_change_cause_id As Object
  300.  
  301. Public Property assoc_asset_id As Object
  302.  
  303. Public Property urgency_name As String
  304.  
  305. Public Property impact_name As String
  306.  
  307. Public Property attachments As List(Of Object)
  308.  
  309. Public Property custom_field As Dictionary(Of String, Object)
  310.  
  311. Public Property tags As List(Of Object)
  312. End Class
  313.  
  314.  
  315. Public Class CcEmail
  316.  
  317. Public Property cc_emails As List(Of String)
  318.  
  319. Public Property fwd_emails As List(Of Object)
  320.  
  321. Public Property reply_cc As List(Of String)
  322.  
  323. Public Property tkt_cc As List(Of String)
  324. End Class
  325.  
  326.  
  327. Public Class TicketResponseRoot
  328.  
  329. Public Property helpdesk_ticket As HelpdeskTicket
  330. End Class
  331.  
  332. Public Class TicketPostResponseRoot
  333.  
  334. Public Property redirect As Object
  335.  
  336. Public Property item As TicketResponseRoot
  337.  
  338. End Class
  339.  
  340. Public Class TicketPutttResponseRoot
  341.  
  342. Public Property ticket As HelpdeskTicket
  343.  
  344. End Class
  345.  
  346. Imports System.IO
  347. Imports System.Net
  348. Imports System.Net.Http
  349. Imports System.Security.Authentication
  350. Imports System.Text
  351.  
  352. Namespace HttpUtils
  353.  
  354. Public Class HttpUtil
  355.  
  356. Public Shared Function SubmitHttpRequest(resourceURL As String,
  357. method As HttpMethod,
  358. basicAuthUser As String,
  359. basicAuthPassword As String,
  360. Optional requestBodyContent As String = Nothing) As HttpWebResponse
  361.  
  362. Dim httpWebrequest As HttpWebRequest = WebRequest.Create(resourceURL)
  363. httpWebrequest.Method = method.Method
  364. httpWebrequest.Accept = "application/json"
  365. httpWebrequest.ContentType = "application/json"
  366. httpWebrequest.Timeout = 25000
  367. Dim basicAuthCreds As String = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(basicAuthUser & ":" & basicAuthPassword))
  368. httpWebrequest.Headers.Add("Authorization", "Basic " + basicAuthCreds)
  369.  
  370.  
  371. If requestBodyContent IsNot Nothing Then
  372. Using writer As New StreamWriter(httpWebrequest.GetRequestStream())
  373. writer.Write(requestBodyContent)
  374. End Using
  375. End If
  376.  
  377.  
  378. Dim httpResponse As HttpWebResponse = Nothing
  379. Try
  380. SetSslProtocal()
  381. httpResponse = httpWebrequest.GetResponse()
  382. Catch WebEx As WebException
  383. Throw New HttpApiException(requestBody:=requestBodyContent,
  384. message:=$"HttpUtil.SubmitHttpRequest -- HTTP Error occurred at {DateTime.Now.ToString()}, see inner exception for details",
  385. innerException:=WebEx)
  386. End Try
  387.  
  388. Return httpResponse
  389.  
  390. End Function
  391.  
  392.  
  393. ''' <summary>
  394. ''' Sets the Security Protocal to avoid error:
  395. ''' "Additional information: The underlying connection was closed: An unexpected error occurred on a send.
  396. ''' (Authentication failed because remote party has closed the transport stream)
  397. ''' See: https://stackoverflow.com/a/47517067/614263
  398. ''' </summary>
  399. Public Shared Sub SetSslProtocal()
  400. Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
  401. Const Tls12 As SecurityProtocolType = DirectCast(_Tls12,
  402. SecurityProtocolType)
  403. ServicePointManager.SecurityProtocol = Tls12
  404. End Sub
  405.  
  406.  
  407. End Class
  408.  
  409.  
  410. End Namespace
Add Comment
Please, Sign In to add comment