timkontrol4

Untitled

Dec 11th, 2018
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.53 KB | None | 0 0
  1. using System;
  2. using System.Configuration;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.IO;
  10.  
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. using RestSharp;
  14. using NLog;
  15.  
  16. using UpviseIntegration.Services.Models;
  17.  
  18. namespace UpviseIntegration.Services
  19. {
  20.     public class UpviseServices
  21.     {
  22.         //These values should never change - indicated to us by Vertical Matters (made constants because of this)
  23.         const string upviseApiURL = "http://alintegrationapi.azurewebsites.net/api/upvise/";
  24.         const string upviseTokenApiURL = "http://alintegrationapi.azurewebsites.net";
  25.  
  26.  
  27.         #region init variables, class methods
  28.         private Logger Log;
  29.         private Logger JobLog;
  30.  
  31.         private UpviseToken _token;
  32.         private UpviseToken token
  33.         {
  34.             get
  35.             {
  36.                 return _token;
  37.             }
  38.             set
  39.             {
  40.                 if (value.access_token != null)
  41.                 {
  42.                     _token = value;
  43.                 }
  44.             }
  45.         }
  46.        
  47.  
  48.         public UpviseServices(string environment = "UAT")
  49.         {
  50.             Log = LogManager.GetLogger("Default");
  51.             JobLog = LogManager.GetLogger("UpviseJobLog");
  52.         }
  53.  
  54.         #endregion
  55.  
  56.         #region helper methods
  57.         public long ToEpoch(DateTime date)
  58.         {
  59.             var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  60.             return Convert.ToInt64((date - epoch).TotalMilliseconds);
  61.         }
  62.         #endregion
  63.  
  64.  
  65.         //Get the upvise token - passing through the environment to get the token for - "UAT" or "PROD"
  66.         //The API lives on the same URL, but when you pass in a different env key, it will access that environment through the env key switch
  67.         #region Get Token
  68.  
  69.         public UpviseToken GetToken(string environment = "UAT")
  70.         {
  71.             UpviseToken retval = new UpviseToken();
  72.             environment = environment.ToUpper();
  73.  
  74.             if (token != null)
  75.             {
  76.                 return token;
  77.             }
  78.  
  79.  
  80.             string username = ConfigurationManager.AppSettings[environment + "_UserName"].ToString();
  81.             string password = ConfigurationManager.AppSettings[environment + "_Password"].ToString();
  82.  
  83.             var client = new RestClient(upviseTokenApiURL);
  84.  
  85.             var request = new RestRequest("token", Method.POST);
  86.             request.AddParameter("username", username);
  87.             request.AddParameter("password", password);
  88.             request.AddParameter("grant_type", "password");
  89.  
  90.             IRestResponse<UpviseToken> tokenResponse = client.Execute<UpviseToken>(request);
  91.  
  92.             if (tokenResponse.StatusCode == HttpStatusCode.OK)
  93.             {
  94.                 retval = tokenResponse.Data;
  95.  
  96.                 //Set the token to what we just received
  97.                 token = retval;
  98.             }
  99.             else
  100.             {
  101.                 throw new Exception(string.Format("Could not retrieve token for username: {0} - Error was: {1}", username, tokenResponse.Content));
  102.             }
  103.             return retval;
  104.         }
  105.         #endregion
  106.  
  107.  
  108.         //GET methods for upvise - GetActiveUpviseForms, GetFormPDF, GetAllUpviseFormTemplates, GetAllProjects, GetAllCompanies
  109.         #region Upvise - GET data methods
  110.         public JArray GetActiveUpviseForms()
  111.         {
  112.             Stopwatch timer = Stopwatch.StartNew();
  113.  
  114.             JArray retval = new JArray();
  115.  
  116.             var client = new RestClient(upviseApiURL);
  117.  
  118.             var request = new RestRequest("Forms", Method.GET);
  119.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  120.             request.AddParameter("editedSince", ToEpoch(DateTime.Now.AddDays(-1))); // anything edited in the last day will be returned
  121.            
  122.  
  123.             IRestResponse response = client.Execute(request);
  124.             string json = response.Content;
  125.             retval = JsonConvert.DeserializeObject<JArray>(json);
  126.  
  127.             timer.Stop();
  128.             Log.Log(LogLevel.Info, string.Format("UpviseServices.GetActiveUpviseForms() - Forms Returned: {0} - Time: {1} milliseconds", retval.Count, timer.ElapsedMilliseconds));
  129.  
  130.             return retval;
  131.         }
  132.  
  133.         public byte[] GetFormPDF(string formID)
  134.         {
  135.             byte[] retval;
  136.  
  137.             var client = new RestClient(upviseApiURL);
  138.  
  139.             var request = new RestRequest("Forms/PDF", Method.POST);
  140.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  141.             request.AddJsonBody(new { id = formID });
  142.  
  143.             IRestResponse response = client.Execute(request);
  144.  
  145.             if (response.StatusCode != HttpStatusCode.OK)
  146.             {
  147.                 switch(response.StatusCode)
  148.                 {
  149.                     case HttpStatusCode.BadRequest: // 400
  150.                         Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- No form with that ID", formID));
  151.                         //System.Diagnostics.Debug.Write(" (" + formID + ") -- No form with that ID");
  152.                         break;
  153.  
  154.                     case HttpStatusCode.InternalServerError: // 500
  155.                         if (response.Content.Contains("an error has occurred"))
  156.                         {
  157.                             Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Upvise API server has crashed", formID));
  158.                             //System.Diagnostics.Debug.Write(" (" + formID + ") -- Upvise API server has crashed");
  159.                         }
  160.                         if (response.Content.Contains("Cannot locate Form"))
  161.                         {
  162.                             Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- No PDF", formID));
  163.                             //System.Diagnostics.Debug.Write(" (" + formID + ") -- No PDF");
  164.                         }
  165.                         break;
  166.  
  167.                     case HttpStatusCode.BadGateway: // 502
  168.                         Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Connection issue", formID));
  169.                             //System.Diagnostics.Debug.Write(" (" + formID + ") -- Connection issue");
  170.                         break;
  171.  
  172.                     case HttpStatusCode.ProxyAuthenticationRequired: // Sophos??
  173.                         Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Proxy auth required", formID));
  174.                             //System.Diagnostics.Debug.Write(" (" + formID + ") -- Proxy auth required");
  175.                         break;
  176.                 }
  177.  
  178.                 retval = null;
  179.             }
  180.             else
  181.             {
  182.                 retval = response.RawBytes;
  183.             }
  184.            
  185.             //string filePath = System.Configuration.ConfigurationManager.AppSettings["DocumentsDirectory"].ToString();
  186.             //filePath = filePath + formID + "." + "pdf";
  187.  
  188.             ////Write the file
  189.             //File.WriteAllBytes(filePath, fileBytes);
  190.             //retval = true;
  191.  
  192.             return retval;
  193.         }
  194.  
  195.         public JArray GetAllUpviseFormTemplates()
  196.         {
  197.             JArray retval = new JArray();
  198.  
  199.             System.Diagnostics.Stopwatch timer = Stopwatch.StartNew();
  200.  
  201.             var client = new RestClient(upviseApiURL);
  202.  
  203.             var request = new RestRequest("Templates", Method.GET);
  204.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  205.             request.AddParameter("editedSince", ToEpoch(DateTime.Now.AddDays(-1))); // anything edited in the last day will be returned
  206.  
  207.             IRestResponse response = client.Execute(request);
  208.             string json = response.Content;
  209.             retval = JsonConvert.DeserializeObject<JArray>(json);
  210.  
  211.             timer.Stop();
  212.             Log.Log(LogLevel.Info, string.Format("UpviseServices.GetAllUpviseFormTemplates() - Templates Returned: {0} - Time: {1} milliseconds", retval.Count, timer.ElapsedMilliseconds));
  213.  
  214.             return retval;
  215.         }
  216.  
  217.         public string GetAllProjects()
  218.         {
  219.             string retval = "";
  220.  
  221.             var client = new RestClient(upviseApiURL);
  222.  
  223.             var request = new RestRequest("Projects", Method.GET);
  224.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  225.  
  226.             IRestResponse response = client.Execute(request);
  227.             string json = response.Content;
  228.             retval = json;
  229.  
  230.             return retval;
  231.         }
  232.  
  233.         public string GetAllCompanies()
  234.         {
  235.             string retval = "";
  236.  
  237.             var client = new RestClient(upviseApiURL);
  238.  
  239.             var request = new RestRequest("Companies", Method.GET);
  240.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  241.  
  242.             IRestResponse response = client.Execute(request);
  243.             string json = response.Content;
  244.             retval = json;
  245.  
  246.             return retval;
  247.         }
  248.  
  249.         #endregion
  250.  
  251.  
  252.         //POST Methods for Upvise - InsertUpdateProject, InsertUpdateVendor, InsertUpdateBulkVendor, InsertUpdateBulkProject
  253.         #region Upvise - POST data methods
  254.         public HttpStatusCode InsertUpdateProject(object obj, int counter)
  255.         {
  256.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  257.  
  258.             Stopwatch timer = Stopwatch.StartNew();
  259.  
  260.             var client = new RestClient(upviseApiURL);
  261.             var request= new RestRequest("Projects", Method.POST);
  262.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  263.  
  264.             //Add body
  265.             request.AddJsonBody(obj);
  266.  
  267.             IRestResponse response = client.Execute(request);
  268.             retval = response.StatusCode;
  269.  
  270.             timer.Stop();
  271.  
  272.             if (retval != HttpStatusCode.OK)
  273.             {
  274.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to process Project({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseProject)obj).id, timer.ElapsedMilliseconds));
  275.             }
  276.             else
  277.             {
  278.                 JobLog.Log(LogLevel.Debug, string.Format("Insert/Update of Project({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseProject)obj).id, timer.ElapsedMilliseconds));
  279.             }
  280.  
  281.             return retval;
  282.         }
  283.  
  284.  
  285.         public HttpStatusCode InsertUpdateVendor(object obj, int counter)
  286.         {
  287.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  288.  
  289.             //Ensure all critical fields do not contain null, else skip vendor
  290.             UpviseCompany v = (UpviseCompany)obj;
  291.             if (v.id == null || v.name == null || v.phone == null || v.street == null)
  292.             {
  293.                 JobLog.Log(LogLevel.Debug, string.Format("Could not process Vendor({0}) with null critical fields (id, name, phone, street). Vendor details were: {1}", counter, ((UpviseCompany)obj).id));
  294.                 return retval;
  295.             }
  296.  
  297.             Stopwatch timer = Stopwatch.StartNew();
  298.  
  299.             var client = new RestClient(upviseApiURL);
  300.             var request = new RestRequest("Companies", Method.POST);
  301.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  302.  
  303.             //Add body
  304.             request.AddJsonBody(obj);
  305.  
  306.  
  307.             IRestResponse response = client.Execute(request);
  308.             retval = response.StatusCode;
  309.  
  310.             timer.Stop();
  311.  
  312.             if (retval != HttpStatusCode.OK)
  313.             {
  314.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to process Vendor({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseCompany)obj).id, timer.ElapsedMilliseconds));
  315.             }
  316.             else
  317.             {
  318.                 JobLog.Log(LogLevel.Debug, string.Format("Insert/Update of Vendor({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseCompany)obj).id, timer.ElapsedMilliseconds));
  319.             }
  320.  
  321.             return retval;
  322.         }
  323.  
  324.         public System.Net.HttpStatusCode InsertUpdateBulkVendor(object obj)
  325.         {
  326.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  327.  
  328.             Stopwatch timer = Stopwatch.StartNew();
  329.  
  330.             var client = new RestClient(upviseApiURL);
  331.             var request = new RestRequest("Companies/CreateMultipleCompanies", Method.POST);
  332.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  333.  
  334.             //Add body
  335.             request.AddJsonBody(obj);
  336.  
  337.             IRestResponse response = client.Execute(request);
  338.             retval = response.StatusCode;
  339.  
  340.             timer.Stop();
  341.  
  342.             if (retval != HttpStatusCode.OK)
  343.             {
  344.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to Bulk Update Vendors. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
  345.             }
  346.             else
  347.             {
  348.                 JobLog.Log(LogLevel.Debug, string.Format("Bulk Insert/Update of Vendors was successful. ({0} milliseconds)", timer.ElapsedMilliseconds));
  349.             }
  350.  
  351.             return retval;
  352.         }
  353.  
  354.         public HttpStatusCode InsertUpdateFormArchive(object obj)
  355.         {
  356.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  357.  
  358.             Stopwatch timer = Stopwatch.StartNew();
  359.  
  360.             var client = new RestClient(upviseApiURL);
  361.             var request = new RestRequest("FormArchive", Method.POST);
  362.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  363.  
  364.             //Add body
  365.             request.AddJsonBody(obj);
  366.  
  367.             IRestResponse response = client.Execute(request);
  368.             retval = response.StatusCode;
  369.  
  370.             timer.Stop();
  371.  
  372.             if (retval != HttpStatusCode.OK)
  373.             {
  374.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to Archive Form. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
  375.             }
  376.             else
  377.             {
  378.                 JobLog.Log(LogLevel.Debug, string.Format("Archive Form was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
  379.             }
  380.  
  381.             return retval;
  382.         }
  383.  
  384.         public HttpStatusCode InsertUpdateFormDearchive(object obj)
  385.         {
  386.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  387.  
  388.             System.Diagnostics.Stopwatch timer = Stopwatch.StartNew();
  389.  
  390.             var client = new RestClient(upviseApiURL);
  391.             var request = new RestRequest("Forms/Dearchive", Method.POST);
  392.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  393.  
  394.             //Add body
  395.             request.AddJsonBody(obj);
  396.  
  397.             IRestResponse response = client.Execute(request);
  398.             retval = response.StatusCode;
  399.  
  400.             timer.Stop();
  401.  
  402.             if (retval != HttpStatusCode.OK)
  403.             {
  404.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to Unarchive Form. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
  405.             }
  406.             else
  407.             {
  408.                 JobLog.Log(LogLevel.Debug, string.Format("Unarchive Form was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
  409.             }
  410.  
  411.             return retval;
  412.         }
  413.  
  414.         public HttpStatusCode InsertUpdateBulkProject(object obj)
  415.         {
  416.             HttpStatusCode retval = HttpStatusCode.InternalServerError;
  417.  
  418.             Stopwatch timer = Stopwatch.StartNew();
  419.  
  420.             var client = new RestClient(upviseApiURL);
  421.             var request = new RestRequest("Projects/CreateMultipleProjects", Method.POST);
  422.             request.AddHeader("Authorization", "Bearer " + token.access_token);
  423.  
  424.             //Add body
  425.             request.AddJsonBody(obj);
  426.  
  427.             IRestResponse response = client.Execute(request);
  428.             retval = response.StatusCode;
  429.  
  430.             timer.Stop();
  431.  
  432.             if (retval != HttpStatusCode.OK)
  433.             {
  434.                 JobLog.Log(LogLevel.Debug, string.Format("Failed to Bulk Update Projects. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
  435.             }
  436.             else
  437.             {
  438.                 JobLog.Log(LogLevel.Debug, string.Format("Bulk Insert/Update of Projects was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
  439.             }
  440.  
  441.             return retval;
  442.         }
  443.  
  444.         #endregion
  445.  
  446.     }
  447. }
Add Comment
Please, Sign In to add comment