Guest User

Untitled

a guest
Jul 25th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.04 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7.  
  8. namespace MyApplication
  9. {
  10. /// <summary>
  11. /// This class is a simple authentication/ticket submission program for ZenDesk.
  12. /// </summary>
  13. class ZenRequest
  14. {
  15. /// <summary>
  16. /// AppConfigFileSettings is class that reads/updates the App.Config file for
  17. /// simple transport of data. You should use more secure means to pass user sessions,
  18. /// this was necessary in my desktop app for GPO purposes.
  19. /// </summary>
  20. AppConfigFileSettings reg = new AppConfigFileSettings();
  21. /// <summary>
  22. /// ZenRequest is our constructor, and for security purposes, we do not allow null at
  23. /// build time.
  24. /// </summary>
  25. /// <param name="userName">Agent or Admin with all ticket access</param>
  26. /// <param name="password">In cleartext. This is a lament's example-- please secure your code!</param>
  27. /// <param name="debug">Are you using the sandbox URL, or the production?</param>
  28. public ZenRequest(String userName, String password, Boolean debug)
  29. {
  30. if (debug == true)
  31. {
  32. zenURL = "<sandbox_url>"; // Replace this string with the URL of your sandbox to test the app.
  33. }
  34. else if (debug == false)
  35. {
  36. zenURL = "<production_url>"; // Replace this string with the URL of your production helpdesk.
  37. }
  38. zenUserName = userName;
  39. zenPassword = password;
  40.  
  41. }
  42. /// <summary>
  43. /// ZenAuth is a general authentication call for your application. This is essentially your
  44. /// "application login", and should be executed once before any commands are posted against the
  45. /// ZenDesk API to speed up the initial call.
  46. ///
  47. /// Remember, your user account must have "all ticket" access for this to work. This is the best
  48. /// method I've found for authenticating a user against ZenDesk.
  49. /// </summary>
  50. /// <returns>
  51. /// On a successful connection, return the ZenDesk Status code. You must handle the status
  52. /// outside of this class.
  53. ///
  54. /// Note: It is possible to get a Status response that does NOT authenticate you, make sure you stay
  55. /// current with the ZenDesk REST API.
  56. /// </returns>
  57. public string ZenAuth()
  58. {
  59. WebClient zenWeb = zenClient(); // See zenClient below for further description.
  60.  
  61. // The next two lines formulate a GET request using the URL we specified at object creation
  62. // as well as the "users.xml" file we use for simple authentication.
  63. String zenFile = "users.xml";
  64. String zenRequest = zenURL + zenFile;
  65.  
  66.  
  67. // This gracefully executes a GET request, and will degrade without an application crash.
  68. try
  69. {
  70. zenWeb.DownloadData(zenRequest); // Start the GET request.
  71.  
  72. return zenWeb.ResponseHeaders["Status"]; // Returns your status code. You want to be
  73. // Checking for a 200 OK.
  74. }
  75. catch (Exception e)
  76. {
  77. return "Error"; // Self explanatory. Handle your error properly.
  78. }
  79.  
  80. }
  81. /// <summary>
  82. /// This method performs two functions: the first is to create a new ticket, using an XML-structured POST.
  83. /// The second function is to return the ticket number for application usage.
  84. /// </summary>
  85. /// <param name="userName">This is the email you will be creating a ticket for.</param>
  86. /// <param name="displayName">How do you want to display the name in ZenDesk?</param>
  87. /// <returns>Status Code for action.</returns>
  88. public String ZenSubmit(String userName, String displayName)
  89. {
  90. WebClient zenWeb = zenClient(); // See zenClient below for more information.
  91.  
  92. // The following lines structure a POST request against tickets.xml. I've also accounted
  93. // for an additional custom ticket field you may have in your helpdesk.
  94. String zenFile = "tickets.xml";
  95. String zenRequest = zenURL + zenFile;
  96. String customTicketField = "";
  97.  
  98. // Remember, "reg" is reading from my app.config-- I strongly recommend using another
  99. // method to store your user session.
  100. if (reg.ReturnAppSettings("userName") == "<specificUser1>") // Check for specific user
  101. // Enter user specific custom field.
  102. {
  103. customTicketField = @"<ticket-field-entry>
  104. <ticket-field-id>[ID for custom ticket field.]</ticket-field-id>
  105. <value>[tag for custom ticket field]</value>
  106. </ticket-field-entry>";
  107. }
  108. else if (reg.ReturnAppSettings("userName") == "<specificUser2>") // See above.
  109. {
  110. customTicketField = @"<ticket-field-entry>
  111. <ticket-field-id>[ID for custom ticket field.]</ticket-field-id>
  112. <value>[tag for custom ticket field]</value>
  113. </ticket-field-entry>";
  114. }
  115. else
  116. {
  117. customTicketField = ""; // Do not enter custom field.
  118. }
  119.  
  120. // The String Literal below constructs the XML needed for a successful POST, based on the
  121. // fields we've already populated above.
  122. String createTicketXML = @"<ticket>
  123. <subject>[Ticket Subject]</subject>
  124. <description>[Body of ticket]</description>
  125. <requester-name>" + displayName + @"</requester-name>
  126. <requester-email>" + userName + @"</requester-email>
  127. <set-tags>[tag to set, if any]</set-tags>
  128. <ticket-field-entries type=""array"">
  129. " + customTicketField + @"
  130. </ticket-field-entries>
  131. </ticket>";
  132. zenWeb.UploadString(zenRequest, createTicketXML); // Execute the POST request, and hopefully create ticket.
  133.  
  134.  
  135. // If the ticket is created successfully, return the ticket number.
  136. // Check the REST API frequently in case the location of the ticket changes.
  137. if (zenWeb.ResponseHeaders["Status"] == "201 Created")
  138. {
  139. zenTicketURL = zenWeb.ResponseHeaders["Location"]; // Returns the ticket location in XML.
  140. // The ticket number is extracted by removing the URL we are using, followed by the tickets/ URI,
  141. // and finally by stripping ".xml" from the remaining string. Again, all of these locations are
  142. // documented in the REST API for ZenDesk.
  143.  
  144. int URLcount = CountChars(zenURL + "tickets/");
  145.  
  146. String returnVar = zenTicketURL;
  147. returnVar = returnVar.Remove(0, URLcount);
  148. char[] xmlChar = { '.', 'x', 'm', 'l' };
  149. returnVar = returnVar.TrimEnd(xmlChar);
  150. return returnVar;
  151. }
  152. else
  153. {
  154. return "FAIL"; // Ticket creation unsuccessful.
  155. }
  156.  
  157. }
  158. /// <summary>
  159. /// This is just an accessory method to get the last ticket created, should you ever need to.
  160. /// </summary>
  161. /// <returns>XML return of last ticket created.</returns>
  162. public String getTicket() {
  163. return zenTicketURL;
  164. }
  165. /// <summary>
  166. /// This method is the most important one in the entire class. Instead of creating a WebClient for every single
  167. /// action I had to take, I opted instead to set the basics up in zenClient, which can then be object referenced
  168. /// with every new call, and extended. This also promises proper garbage collection from the program, disposing of
  169. /// queries after they have been executed.
  170. /// </summary>
  171. /// <returns>Default settings for all WebClients</returns>
  172. private WebClient zenClient()
  173. {
  174. WebClient zenPrimaryClient = new WebClient(); // WebClient will provide transport for GET/POST commands.
  175. zenPrimaryClient.Credentials = new System.Net.NetworkCredential(zenUserName, zenPassword); // Secures UserName and Password for usage.
  176. zenPrimaryClient.Headers.Add("Content-Type", "application/xml"); // Set your MIME type.
  177.  
  178. zenPrimaryClient.BaseAddress = zenURL; // Set the Base URL for all commands.
  179.  
  180. return zenPrimaryClient; // Return all settings.
  181. }
  182.  
  183. /// <summary>
  184. /// Generic method to count all characters in a string, and account for all spaces.
  185. /// Recommended for usage with URLs.
  186. /// </summary>
  187. /// <param name="value">URL to check</param>
  188. /// <returns>Characters in String/URL</returns>
  189. static int CountChars(string value)
  190. {
  191. int result = 0;
  192. bool lastWasSpace = false;
  193.  
  194. foreach (char c in value)
  195. {
  196. if (char.IsWhiteSpace(c))
  197. {
  198. if (lastWasSpace == false)
  199. {
  200. result++;
  201. }
  202. lastWasSpace = true;
  203. }
  204. else
  205. {
  206. result++;
  207. lastWasSpace = false;
  208. }
  209. }
  210. return result;
  211. }
  212.  
  213. #region Declarations
  214. private String zenTicketURL;
  215. private String zenUserName;
  216. private String zenPassword;
  217. private String zenURL;
  218. #endregion
  219. }
  220. }
Add Comment
Please, Sign In to add comment