Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.75 KB | None | 0 0
  1. using cloudbeatapi.Models;
  2. using Microsoft.WindowsAzure.Storage;
  3. using Microsoft.WindowsAzure.Storage.Queue;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Linq;
  6. using Swashbuckle.Swagger;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Http;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Web;
  17. using System.Web.Helpers;
  18. using System.Web.Http;
  19. using System.Web.Mvc;
  20. using System.Web.Script.Serialization;
  21.  
  22. namespace cloudbeatapi.Controllers
  23. {
  24. public class WirelessEventController : ApiController
  25. {
  26.  
  27.  
  28. [System.Web.Mvc.HttpPost]
  29. [APIAuthenticationFilter]
  30. public HttpResponseMessage Post(FormCollection formCollection, HttpRequestMessage request, string id)
  31. {
  32. int studyId = 0;
  33. //Testing
  34. try
  35. {
  36. // hea_file, json_file, atr_file, dat_file
  37. var jsonFile = HttpContext.Current.Request.Form.Get("json_file");
  38. var heaFile = HttpContext.Current.Request.Form.Get("hea_file");
  39. var atrFile = HttpContext.Current.Request.Form.Get("atr_file");
  40. var datFile = HttpContext.Current.Request.Form.Get("dat_file");
  41.  
  42.  
  43. var context = new StorageContext();
  44. var blobContainer = context.BlobClient.GetContainerReference("application-logs");
  45. blobContainer.CreateIfNotExists();
  46.  
  47. var blob = blobContainer.GetAppendBlobReference("WirelessEvent/log.txt");
  48.  
  49. if (!blob.Exists())
  50. {
  51. blob.CreateOrReplace();
  52. }
  53.  
  54.  
  55. string newLog = Environment.NewLine +
  56. "New Request: " + DateTime.Now + Environment.NewLine +
  57. "Id: " + id;
  58.  
  59. // blob.UploadText(newLog);
  60.  
  61. OperationContext ctxt = new OperationContext();
  62. ctxt.SendingRequest += (sender, e) =>
  63. {
  64. e.Request.Headers["if-match"] = "*";
  65. };
  66.  
  67. using (AutoResetEvent waitHandle = new AutoResetEvent(false))
  68. {
  69.  
  70. var result = blob.BeginAppendText(newLog, Encoding.UTF8, null, null, ctxt,
  71. ar => waitHandle.Set(),
  72. null);
  73. waitHandle.WaitOne();
  74. blob.EndAppendText(result);
  75.  
  76.  
  77. }
  78.  
  79. //Get the studyId of the device running
  80. studyId = Functions.GetStudyId(id.Split('_')[0]);
  81.  
  82. //Upload the header
  83. var folderName = id + "_" + studyId + "_" + DateTime.UtcNow.Year + DateTime.UtcNow.Month.ToString("00") + DateTime.UtcNow.Day.ToString("00") + DateTime.UtcNow.Hour.ToString("00") + DateTime.UtcNow.Minute.ToString("00") + DateTime.UtcNow.Second.ToString("00");
  84. var fileName = studyId + "/ecg/" + folderName + "/" + folderName;
  85. // Create the blob client.
  86. blobContainer = context.BlobClient.GetContainerReference("studies");
  87. var eventBlob = blobContainer.GetBlockBlobReference(fileName + ".hea");
  88.  
  89. byte[] paramBytes = Convert.FromBase64String(heaFile);
  90.  
  91. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  92.  
  93. //Upload the json if it exists
  94. if (jsonFile != null)
  95. {
  96. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".json");
  97. paramBytes = Convert.FromBase64String(jsonFile);
  98. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  99. }
  100.  
  101.  
  102. //Upload the atr file if it exists
  103. if (atrFile != null)
  104. {
  105. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".atr");
  106. paramBytes = Convert.FromBase64String(atrFile);
  107. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  108. }
  109.  
  110.  
  111. //Upload the data file
  112. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".dat");
  113. paramBytes = Convert.FromBase64String(datFile);
  114. eventBlob.UploadFromByteArray(paramBytes, 0, paramBytes.Length, null);
  115.  
  116. //Create a Queue Message
  117. CloudQueueClient queueClient = context.QueueClient;
  118. // Retrieve a reference to a queue
  119. CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
  120. // Create the queue if it doesn't already exist
  121. queue.CreateIfNotExists();
  122. // Create a message and add it to the queue.
  123. CloudQueueMessage queueMessage = new CloudQueueMessage(fileName);
  124. queue.AddMessage(queueMessage);
  125.  
  126. //Returned Message
  127. HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
  128. string yourJson = "{\"Result\":\"Success\"}";
  129.  
  130. message.Content = new StringContent(yourJson);
  131.  
  132. return message;
  133. }
  134. catch (Exception ex)
  135. {
  136. var storageContext = new StorageContext();
  137. var studiesContainer = storageContext.BlobClient.GetContainerReference("studies");
  138. string exceptionMessage = ex.Message;
  139.  
  140. var errorFile = studiesContainer.GetAppendBlobReference(studyId + "/error.csv");
  141.  
  142. if (!errorFile.Exists())
  143. {
  144. errorFile.CreateOrReplace();
  145. }
  146. errorFile.Properties.CacheControl = "no-cache";
  147. errorFile.SetProperties();
  148. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("Error:" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine)))
  149. {
  150. errorFile.AppendBlock(ms);
  151. }
  152.  
  153. HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
  154.  
  155. return message;
  156. }
  157.  
  158. // return yourJson;
  159.  
  160.  
  161. }
  162.  
  163.  
  164. [System.Web.Mvc.HttpPost]
  165. [APIAuthenticationFilter]
  166. public async Task<HttpResponseMessage> PostAsync(HttpRequestMessage request, string device_serial)
  167. {
  168. string jsonFile = "";
  169. string heaFile = "";
  170. string atrFile = "";
  171. string datFile = "";
  172. HttpPostedFile _jsonFile = null;
  173. HttpPostedFile _heaFile = null;
  174. HttpPostedFile _atrFile = null;
  175. HttpPostedFile _datFile = null;
  176.  
  177. bool decode = true;
  178.  
  179. jsonFile = HttpContext.Current.Request.Form.Get("json_file");
  180. heaFile = HttpContext.Current.Request.Form.Get("hea_file");
  181. atrFile = HttpContext.Current.Request.Form.Get("atr_file");
  182. datFile = HttpContext.Current.Request.Form.Get("dat_file");
  183.  
  184. if (heaFile == null)
  185. {
  186. decode = false;
  187. // hea_file, json_file, atr_file, dat_file
  188. var count = HttpContext.Current.Request.Files.Count;
  189. var keys = HttpContext.Current.Request.Files.AllKeys;
  190.  
  191. _heaFile = HttpContext.Current.Request.Files.Get("event_hea");
  192. _jsonFile = HttpContext.Current.Request.Files.Get("event_json");
  193. _atrFile = HttpContext.Current.Request.Files.Get("event_atr");
  194.  
  195. if (_jsonFile != null)
  196. {
  197. jsonFile = new StreamReader(_jsonFile.InputStream).ReadToEnd();
  198. }
  199. if (_heaFile != null)
  200. {
  201. heaFile = new StreamReader(_heaFile.InputStream).ReadToEnd();
  202. }
  203. if (_atrFile != null)
  204. {
  205. atrFile = new StreamReader(_atrFile.InputStream).ReadToEnd();
  206. }
  207. _datFile = HttpContext.Current.Request.Files.Get("event_dat");
  208.  
  209.  
  210. //foreach (var key in keys)
  211. //{
  212. // heaFile += "key:" + key + " ";
  213. //}
  214. //heaFile += "COUNT: " + count;
  215. //heaFile += " KEYS: " + keys;
  216.  
  217. //heaFile += " JSON: " + jsonFile;
  218. //heaFile += " ATR: " + atrFile;
  219. }
  220.  
  221.  
  222. var context = new StorageContext();
  223. var blobContainer = context.BlobClient.GetContainerReference("application-logs");
  224. blobContainer.CreateIfNotExists();
  225.  
  226. var blob = blobContainer.GetAppendBlobReference("WirelessEvent/log.txt");
  227.  
  228. if (!blob.Exists())
  229. {
  230. blob.CreateOrReplace();
  231. }
  232.  
  233.  
  234. string newLog = Environment.NewLine +
  235. "New Request: " + DateTime.Now + Environment.NewLine +
  236. "Id: " + device_serial;
  237.  
  238. // blob.UploadText(newLog);
  239.  
  240. OperationContext ctxt = new OperationContext();
  241. ctxt.SendingRequest += (sender, e) =>
  242. {
  243. e.Request.Headers["if-match"] = "*";
  244. };
  245.  
  246. using (AutoResetEvent waitHandle = new AutoResetEvent(false))
  247. {
  248.  
  249. var result = blob.BeginAppendText(newLog, Encoding.UTF8, null, null, ctxt,
  250. ar => waitHandle.Set(),
  251. null);
  252. waitHandle.WaitOne();
  253. blob.EndAppendText(result);
  254.  
  255.  
  256. }
  257. bool JustAnnotations = false;
  258. byte[] paramBytes;
  259. if (decode)
  260. {
  261. paramBytes = Convert.FromBase64String(jsonFile);
  262. }
  263. if (jsonFile != null)
  264. {
  265. JObject jsonObject;
  266. if (decode)
  267. {
  268. paramBytes = Convert.FromBase64String(jsonFile);
  269. jsonObject = JObject.Parse(Encoding.UTF8.GetString(paramBytes));
  270. }
  271. else
  272. {
  273. jsonObject = JObject.Parse(jsonFile);
  274. }
  275. JObject timeInfo = (JObject)jsonObject["Time"];
  276. string EventTypeString = (string)timeInfo["Event type"];
  277. string fileNameAnnotations = "";
  278. if (EventTypeString.Equals("Annotations") || _datFile == null)
  279. {
  280. JustAnnotations = true;
  281. //Get the studyId of the device running
  282. var studyIdAnnotations = Functions.GetStudyId(device_serial.Split('_')[0]);
  283.  
  284. //var studyStarted = Functions.CheckIfStudyStarted(studyIdAnnotations);
  285. //if (!studyStarted)
  286. //{
  287. // studyIdAnnotations = 0;
  288. //}
  289. //Upload the header
  290. var folderNameAnnotations = device_serial + "_" + studyIdAnnotations + "_" + DateTime.UtcNow.Year + DateTime.UtcNow.Month.ToString("00") + DateTime.UtcNow.Day.ToString("00") + DateTime.UtcNow.Hour.ToString("00") + DateTime.UtcNow.Minute.ToString("00") + DateTime.UtcNow.Second.ToString("00");
  291. fileNameAnnotations = studyIdAnnotations + "/annotations/" + folderNameAnnotations + "/" + folderNameAnnotations + "ann";
  292. // Create the blob client.
  293. blobContainer = context.BlobClient.GetContainerReference("studies");
  294. var eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".hea");
  295.  
  296. if (decode)
  297. {
  298. paramBytes = Convert.FromBase64String(heaFile);
  299. eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
  300.  
  301.  
  302. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".json");
  303. paramBytes = Convert.FromBase64String(jsonFile);
  304. eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
  305.  
  306. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".atr");
  307. paramBytes = Convert.FromBase64String(atrFile);
  308. eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
  309.  
  310. if (datFile != null)
  311. {
  312. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".dat");
  313. paramBytes = Convert.FromBase64String(datFile);
  314. eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
  315. }
  316.  
  317. }
  318. else
  319. {
  320. eventBlobAnnotations.UploadText(heaFile);
  321.  
  322. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".json");
  323. eventBlobAnnotations.UploadText(jsonFile);
  324.  
  325. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".atr");
  326. var streamContentsAtr = _atrFile.InputStream;
  327. streamContentsAtr.Position = 0;
  328. await eventBlobAnnotations.UploadFromStreamAsync(streamContentsAtr);
  329.  
  330. _datFile = HttpContext.Current.Request.Files.Get("event_dat");
  331. if (_datFile != null)
  332. {
  333. var streamContentsDat = _datFile.InputStream;
  334. eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".dat");
  335. streamContentsDat.Position = 0;
  336. await eventBlobAnnotations.UploadFromStreamAsync(streamContentsDat);
  337. }
  338. }
  339.  
  340. //Create a Queue Message
  341. CloudQueueClient queueClient = context.QueueClient;
  342. // Retrieve a reference to a queue
  343. CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
  344. // Create the queue if it doesn't already exist
  345. queue.CreateIfNotExists();
  346. // Create a message and add it to the queue.
  347. CloudQueueMessage queueMessage = new CloudQueueMessage(fileNameAnnotations);
  348. queue.AddMessage(queueMessage);
  349. }
  350. else
  351. {
  352. JustAnnotations = false;
  353. //If we were requesting data, increment actions count when data is received.
  354. if (EventTypeString.Equals("Request"))
  355. {
  356. using (var DBcontext = new LifeSenseDBEntities())
  357. {
  358. var studyId = Functions.GetStudyId(device_serial.Split('_')[0]);
  359. var study = DBcontext.Studies.FirstOrDefault(o => o.Id == studyId);
  360. int actionCount = study.ActionsCount.Value;
  361. actionCount++;
  362. study.ActionsCount = actionCount;
  363. DBcontext.Entry(study).CurrentValues.SetValues(study);
  364. DBcontext.SaveChanges();
  365. }
  366. }
  367.  
  368. }
  369. }
  370.  
  371. if(!JustAnnotations)
  372. {
  373.  
  374. _datFile = HttpContext.Current.Request.Files.Get("event_dat");
  375. Stream streamContentsDat = null;
  376. if (_datFile != null)
  377. {
  378. streamContentsDat = _datFile.InputStream;
  379. datFile = new StreamReader(_datFile.InputStream).ReadToEnd();
  380. }
  381. _atrFile = HttpContext.Current.Request.Files.Get("event_atr");
  382. var streamContentsAtr = _atrFile.InputStream;
  383.  
  384.  
  385.  
  386. //Get the studyId of the device running
  387. var studyId = Functions.GetStudyId(device_serial.Split('_')[0]);
  388. // var studyStarted = Functions.CheckIfStudyStarted(studyId);
  389.  
  390. string fileName = "";
  391. //if (!studyStarted)
  392. //{
  393. // studyId = 0;
  394. //}
  395. //Upload the header
  396. var folderName = device_serial + "_" + studyId + "_" + DateTime.UtcNow.Year + DateTime.UtcNow.Month.ToString("00") + DateTime.UtcNow.Day.ToString("00") + DateTime.UtcNow.Hour.ToString("00") + DateTime.UtcNow.Minute.ToString("00") + DateTime.UtcNow.Second.ToString("00");
  397. fileName = studyId + "/ecg/" + folderName + "/" + folderName;
  398. // Create the blob client.
  399. blobContainer = context.BlobClient.GetContainerReference("studies");
  400. var eventBlob = blobContainer.GetBlockBlobReference(fileName + ".hea");
  401.  
  402. if (decode)
  403. {
  404. paramBytes = Convert.FromBase64String(heaFile);
  405.  
  406. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  407. }
  408. else
  409. {
  410. eventBlob.UploadText(heaFile);
  411. }
  412. //Upload the json if it exists
  413. if (jsonFile != null)
  414. {
  415. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".json");
  416. if (decode)
  417. {
  418. paramBytes = Convert.FromBase64String(jsonFile);
  419. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  420. }
  421. else
  422. {
  423. eventBlob.UploadText(jsonFile);
  424. }
  425. }
  426.  
  427.  
  428. //Upload the atr file if it exists
  429. if (atrFile != null)
  430. {
  431. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".atr");
  432. if (decode)
  433. {
  434. paramBytes = Convert.FromBase64String(atrFile);
  435. eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
  436. }
  437. else
  438. {
  439. streamContentsAtr.Position = 0;
  440. await eventBlob.UploadFromStreamAsync(streamContentsAtr);
  441. }
  442. }
  443.  
  444.  
  445. //Upload the data file
  446. if (datFile != null)
  447. {
  448. eventBlob = blobContainer.GetBlockBlobReference(fileName + ".dat");
  449. if (decode)
  450. {
  451. paramBytes = Convert.FromBase64String(datFile);
  452. eventBlob.UploadFromByteArray(paramBytes, 0, paramBytes.Length, null);
  453. }
  454. else
  455. {
  456. streamContentsDat.Position = 0;
  457. await eventBlob.UploadFromStreamAsync(streamContentsDat);
  458. }
  459. }
  460.  
  461. //Create a Queue Message
  462. CloudQueueClient queueClient = context.QueueClient;
  463. // Retrieve a reference to a queue
  464. CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
  465. // Create the queue if it doesn't already exist
  466. queue.CreateIfNotExists();
  467. // Create a message and add it to the queue.
  468. CloudQueueMessage queueMessage = new CloudQueueMessage(fileName);
  469. queue.AddMessage(queueMessage);
  470.  
  471. }
  472.  
  473.  
  474. //Returned Message
  475. HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
  476. string yourJson = "{\"result\":\"Success\"}";
  477.  
  478. message.Content = new StringContent(yourJson);
  479.  
  480. return message;
  481.  
  482. // return yourJson;
  483.  
  484.  
  485. }
  486.  
  487.  
  488. }
  489. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement