Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Configuration;
- using System.Diagnostics;
- using System.Net;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using RestSharp;
- using NLog;
- using UpviseIntegration.Services.Models;
- namespace UpviseIntegration.Services
- {
- public class UpviseServices
- {
- //These values should never change - indicated to us by Vertical Matters (made constants because of this)
- const string upviseApiURL = "http://alintegrationapi.azurewebsites.net/api/upvise/";
- const string upviseTokenApiURL = "http://alintegrationapi.azurewebsites.net";
- #region init variables, class methods
- private Logger Log;
- private Logger JobLog;
- private UpviseToken _token;
- private UpviseToken token
- {
- get
- {
- return _token;
- }
- set
- {
- if (value.access_token != null)
- {
- _token = value;
- }
- }
- }
- public UpviseServices(string environment = "UAT")
- {
- Log = LogManager.GetLogger("Default");
- JobLog = LogManager.GetLogger("UpviseJobLog");
- }
- #endregion
- #region helper methods
- public long ToEpoch(DateTime date)
- {
- var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- return Convert.ToInt64((date - epoch).TotalMilliseconds);
- }
- #endregion
- //Get the upvise token - passing through the environment to get the token for - "UAT" or "PROD"
- //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
- #region Get Token
- public UpviseToken GetToken(string environment = "UAT")
- {
- UpviseToken retval = new UpviseToken();
- environment = environment.ToUpper();
- if (token != null)
- {
- return token;
- }
- string username = ConfigurationManager.AppSettings[environment + "_UserName"].ToString();
- string password = ConfigurationManager.AppSettings[environment + "_Password"].ToString();
- var client = new RestClient(upviseTokenApiURL);
- var request = new RestRequest("token", Method.POST);
- request.AddParameter("username", username);
- request.AddParameter("password", password);
- request.AddParameter("grant_type", "password");
- IRestResponse<UpviseToken> tokenResponse = client.Execute<UpviseToken>(request);
- if (tokenResponse.StatusCode == HttpStatusCode.OK)
- {
- retval = tokenResponse.Data;
- //Set the token to what we just received
- token = retval;
- }
- else
- {
- throw new Exception(string.Format("Could not retrieve token for username: {0} - Error was: {1}", username, tokenResponse.Content));
- }
- return retval;
- }
- #endregion
- //GET methods for upvise - GetActiveUpviseForms, GetFormPDF, GetAllUpviseFormTemplates, GetAllProjects, GetAllCompanies
- #region Upvise - GET data methods
- public JArray GetActiveUpviseForms()
- {
- Stopwatch timer = Stopwatch.StartNew();
- JArray retval = new JArray();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Forms", Method.GET);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- request.AddParameter("editedSince", ToEpoch(DateTime.Now.AddDays(-1))); // anything edited in the last day will be returned
- IRestResponse response = client.Execute(request);
- string json = response.Content;
- retval = JsonConvert.DeserializeObject<JArray>(json);
- timer.Stop();
- Log.Log(LogLevel.Info, string.Format("UpviseServices.GetActiveUpviseForms() - Forms Returned: {0} - Time: {1} milliseconds", retval.Count, timer.ElapsedMilliseconds));
- return retval;
- }
- public byte[] GetFormPDF(string formID)
- {
- byte[] retval;
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Forms/PDF", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- request.AddJsonBody(new { id = formID });
- IRestResponse response = client.Execute(request);
- if (response.StatusCode != HttpStatusCode.OK)
- {
- switch(response.StatusCode)
- {
- case HttpStatusCode.BadRequest: // 400
- Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- No form with that ID", formID));
- //System.Diagnostics.Debug.Write(" (" + formID + ") -- No form with that ID");
- break;
- case HttpStatusCode.InternalServerError: // 500
- if (response.Content.Contains("an error has occurred"))
- {
- Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Upvise API server has crashed", formID));
- //System.Diagnostics.Debug.Write(" (" + formID + ") -- Upvise API server has crashed");
- }
- if (response.Content.Contains("Cannot locate Form"))
- {
- Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- No PDF", formID));
- //System.Diagnostics.Debug.Write(" (" + formID + ") -- No PDF");
- }
- break;
- case HttpStatusCode.BadGateway: // 502
- Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Connection issue", formID));
- //System.Diagnostics.Debug.Write(" (" + formID + ") -- Connection issue");
- break;
- case HttpStatusCode.ProxyAuthenticationRequired: // Sophos??
- Log.Log(LogLevel.Warn, string.Format("UpviseServices.GetFormPDF() - {0} -- Proxy auth required", formID));
- //System.Diagnostics.Debug.Write(" (" + formID + ") -- Proxy auth required");
- break;
- }
- retval = null;
- }
- else
- {
- retval = response.RawBytes;
- }
- //string filePath = System.Configuration.ConfigurationManager.AppSettings["DocumentsDirectory"].ToString();
- //filePath = filePath + formID + "." + "pdf";
- ////Write the file
- //File.WriteAllBytes(filePath, fileBytes);
- //retval = true;
- return retval;
- }
- public JArray GetAllUpviseFormTemplates()
- {
- JArray retval = new JArray();
- System.Diagnostics.Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Templates", Method.GET);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- request.AddParameter("editedSince", ToEpoch(DateTime.Now.AddDays(-1))); // anything edited in the last day will be returned
- IRestResponse response = client.Execute(request);
- string json = response.Content;
- retval = JsonConvert.DeserializeObject<JArray>(json);
- timer.Stop();
- Log.Log(LogLevel.Info, string.Format("UpviseServices.GetAllUpviseFormTemplates() - Templates Returned: {0} - Time: {1} milliseconds", retval.Count, timer.ElapsedMilliseconds));
- return retval;
- }
- public string GetAllProjects()
- {
- string retval = "";
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Projects", Method.GET);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- IRestResponse response = client.Execute(request);
- string json = response.Content;
- retval = json;
- return retval;
- }
- public string GetAllCompanies()
- {
- string retval = "";
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Companies", Method.GET);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- IRestResponse response = client.Execute(request);
- string json = response.Content;
- retval = json;
- return retval;
- }
- #endregion
- //POST Methods for Upvise - InsertUpdateProject, InsertUpdateVendor, InsertUpdateBulkVendor, InsertUpdateBulkProject
- #region Upvise - POST data methods
- public HttpStatusCode InsertUpdateProject(object obj, int counter)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request= new RestRequest("Projects", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to process Project({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseProject)obj).id, timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Insert/Update of Project({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseProject)obj).id, timer.ElapsedMilliseconds));
- }
- return retval;
- }
- public HttpStatusCode InsertUpdateVendor(object obj, int counter)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- //Ensure all critical fields do not contain null, else skip vendor
- UpviseCompany v = (UpviseCompany)obj;
- if (v.id == null || v.name == null || v.phone == null || v.street == null)
- {
- 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));
- return retval;
- }
- Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Companies", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to process Vendor({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseCompany)obj).id, timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Insert/Update of Vendor({0}) with details: {1} ({2} milliseconds)", counter, ((UpviseCompany)obj).id, timer.ElapsedMilliseconds));
- }
- return retval;
- }
- public System.Net.HttpStatusCode InsertUpdateBulkVendor(object obj)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Companies/CreateMultipleCompanies", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to Bulk Update Vendors. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Bulk Insert/Update of Vendors was successful. ({0} milliseconds)", timer.ElapsedMilliseconds));
- }
- return retval;
- }
- public HttpStatusCode InsertUpdateFormArchive(object obj)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("FormArchive", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to Archive Form. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Archive Form was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
- }
- return retval;
- }
- public HttpStatusCode InsertUpdateFormDearchive(object obj)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- System.Diagnostics.Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Forms/Dearchive", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to Unarchive Form. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Unarchive Form was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
- }
- return retval;
- }
- public HttpStatusCode InsertUpdateBulkProject(object obj)
- {
- HttpStatusCode retval = HttpStatusCode.InternalServerError;
- Stopwatch timer = Stopwatch.StartNew();
- var client = new RestClient(upviseApiURL);
- var request = new RestRequest("Projects/CreateMultipleProjects", Method.POST);
- request.AddHeader("Authorization", "Bearer " + token.access_token);
- //Add body
- request.AddJsonBody(obj);
- IRestResponse response = client.Execute(request);
- retval = response.StatusCode;
- timer.Stop();
- if (retval != HttpStatusCode.OK)
- {
- JobLog.Log(LogLevel.Debug, string.Format("Failed to Bulk Update Projects. Error was - {0}. ({1} milliseconds)", timer.ElapsedMilliseconds));
- }
- else
- {
- JobLog.Log(LogLevel.Debug, string.Format("Bulk Insert/Update of Projects was successful. Response was - {0} ({1} milliseconds)", response.Content, timer.ElapsedMilliseconds));
- }
- return retval;
- }
- #endregion
- }
- }
Add Comment
Please, Sign In to add comment