Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using cloudbeatapi.Models;
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Queue;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using Swashbuckle.Swagger;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Helpers;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Web.Script.Serialization;
- namespace cloudbeatapi.Controllers
- {
- public class WirelessEventController : ApiController
- {
- [System.Web.Mvc.HttpPost]
- [APIAuthenticationFilter]
- public HttpResponseMessage Post(FormCollection formCollection, HttpRequestMessage request, string id)
- {
- int studyId = 0;
- //Testing
- try
- {
- // hea_file, json_file, atr_file, dat_file
- var jsonFile = HttpContext.Current.Request.Form.Get("json_file");
- var heaFile = HttpContext.Current.Request.Form.Get("hea_file");
- var atrFile = HttpContext.Current.Request.Form.Get("atr_file");
- var datFile = HttpContext.Current.Request.Form.Get("dat_file");
- var context = new StorageContext();
- var blobContainer = context.BlobClient.GetContainerReference("application-logs");
- blobContainer.CreateIfNotExists();
- var blob = blobContainer.GetAppendBlobReference("WirelessEvent/log.txt");
- if (!blob.Exists())
- {
- blob.CreateOrReplace();
- }
- string newLog = Environment.NewLine +
- "New Request: " + DateTime.Now + Environment.NewLine +
- "Id: " + id;
- // blob.UploadText(newLog);
- OperationContext ctxt = new OperationContext();
- ctxt.SendingRequest += (sender, e) =>
- {
- e.Request.Headers["if-match"] = "*";
- };
- using (AutoResetEvent waitHandle = new AutoResetEvent(false))
- {
- var result = blob.BeginAppendText(newLog, Encoding.UTF8, null, null, ctxt,
- ar => waitHandle.Set(),
- null);
- waitHandle.WaitOne();
- blob.EndAppendText(result);
- }
- //Get the studyId of the device running
- studyId = Functions.GetStudyId(id.Split('_')[0]);
- //Upload the header
- 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");
- var fileName = studyId + "/ecg/" + folderName + "/" + folderName;
- // Create the blob client.
- blobContainer = context.BlobClient.GetContainerReference("studies");
- var eventBlob = blobContainer.GetBlockBlobReference(fileName + ".hea");
- byte[] paramBytes = Convert.FromBase64String(heaFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- //Upload the json if it exists
- if (jsonFile != null)
- {
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".json");
- paramBytes = Convert.FromBase64String(jsonFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- //Upload the atr file if it exists
- if (atrFile != null)
- {
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".atr");
- paramBytes = Convert.FromBase64String(atrFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- //Upload the data file
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".dat");
- paramBytes = Convert.FromBase64String(datFile);
- eventBlob.UploadFromByteArray(paramBytes, 0, paramBytes.Length, null);
- //Create a Queue Message
- CloudQueueClient queueClient = context.QueueClient;
- // Retrieve a reference to a queue
- CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
- // Create the queue if it doesn't already exist
- queue.CreateIfNotExists();
- // Create a message and add it to the queue.
- CloudQueueMessage queueMessage = new CloudQueueMessage(fileName);
- queue.AddMessage(queueMessage);
- //Returned Message
- HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
- string yourJson = "{\"Result\":\"Success\"}";
- message.Content = new StringContent(yourJson);
- return message;
- }
- catch (Exception ex)
- {
- var storageContext = new StorageContext();
- var studiesContainer = storageContext.BlobClient.GetContainerReference("studies");
- string exceptionMessage = ex.Message;
- var errorFile = studiesContainer.GetAppendBlobReference(studyId + "/error.csv");
- if (!errorFile.Exists())
- {
- errorFile.CreateOrReplace();
- }
- errorFile.Properties.CacheControl = "no-cache";
- errorFile.SetProperties();
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("Error:" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine)))
- {
- errorFile.AppendBlock(ms);
- }
- HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
- return message;
- }
- // return yourJson;
- }
- [System.Web.Mvc.HttpPost]
- [APIAuthenticationFilter]
- public async Task<HttpResponseMessage> PostAsync(HttpRequestMessage request, string device_serial)
- {
- string jsonFile = "";
- string heaFile = "";
- string atrFile = "";
- string datFile = "";
- HttpPostedFile _jsonFile = null;
- HttpPostedFile _heaFile = null;
- HttpPostedFile _atrFile = null;
- HttpPostedFile _datFile = null;
- bool decode = true;
- jsonFile = HttpContext.Current.Request.Form.Get("json_file");
- heaFile = HttpContext.Current.Request.Form.Get("hea_file");
- atrFile = HttpContext.Current.Request.Form.Get("atr_file");
- datFile = HttpContext.Current.Request.Form.Get("dat_file");
- if (heaFile == null)
- {
- decode = false;
- // hea_file, json_file, atr_file, dat_file
- var count = HttpContext.Current.Request.Files.Count;
- var keys = HttpContext.Current.Request.Files.AllKeys;
- _heaFile = HttpContext.Current.Request.Files.Get("event_hea");
- _jsonFile = HttpContext.Current.Request.Files.Get("event_json");
- _atrFile = HttpContext.Current.Request.Files.Get("event_atr");
- if (_jsonFile != null)
- {
- jsonFile = new StreamReader(_jsonFile.InputStream).ReadToEnd();
- }
- if (_heaFile != null)
- {
- heaFile = new StreamReader(_heaFile.InputStream).ReadToEnd();
- }
- if (_atrFile != null)
- {
- atrFile = new StreamReader(_atrFile.InputStream).ReadToEnd();
- }
- _datFile = HttpContext.Current.Request.Files.Get("event_dat");
- //foreach (var key in keys)
- //{
- // heaFile += "key:" + key + " ";
- //}
- //heaFile += "COUNT: " + count;
- //heaFile += " KEYS: " + keys;
- //heaFile += " JSON: " + jsonFile;
- //heaFile += " ATR: " + atrFile;
- }
- var context = new StorageContext();
- var blobContainer = context.BlobClient.GetContainerReference("application-logs");
- blobContainer.CreateIfNotExists();
- var blob = blobContainer.GetAppendBlobReference("WirelessEvent/log.txt");
- if (!blob.Exists())
- {
- blob.CreateOrReplace();
- }
- string newLog = Environment.NewLine +
- "New Request: " + DateTime.Now + Environment.NewLine +
- "Id: " + device_serial;
- // blob.UploadText(newLog);
- OperationContext ctxt = new OperationContext();
- ctxt.SendingRequest += (sender, e) =>
- {
- e.Request.Headers["if-match"] = "*";
- };
- using (AutoResetEvent waitHandle = new AutoResetEvent(false))
- {
- var result = blob.BeginAppendText(newLog, Encoding.UTF8, null, null, ctxt,
- ar => waitHandle.Set(),
- null);
- waitHandle.WaitOne();
- blob.EndAppendText(result);
- }
- bool JustAnnotations = false;
- byte[] paramBytes;
- if (decode)
- {
- paramBytes = Convert.FromBase64String(jsonFile);
- }
- if (jsonFile != null)
- {
- JObject jsonObject;
- if (decode)
- {
- paramBytes = Convert.FromBase64String(jsonFile);
- jsonObject = JObject.Parse(Encoding.UTF8.GetString(paramBytes));
- }
- else
- {
- jsonObject = JObject.Parse(jsonFile);
- }
- JObject timeInfo = (JObject)jsonObject["Time"];
- string EventTypeString = (string)timeInfo["Event type"];
- string fileNameAnnotations = "";
- if (EventTypeString.Equals("Annotations") || _datFile == null)
- {
- JustAnnotations = true;
- //Get the studyId of the device running
- var studyIdAnnotations = Functions.GetStudyId(device_serial.Split('_')[0]);
- //var studyStarted = Functions.CheckIfStudyStarted(studyIdAnnotations);
- //if (!studyStarted)
- //{
- // studyIdAnnotations = 0;
- //}
- //Upload the header
- 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");
- fileNameAnnotations = studyIdAnnotations + "/annotations/" + folderNameAnnotations + "/" + folderNameAnnotations + "ann";
- // Create the blob client.
- blobContainer = context.BlobClient.GetContainerReference("studies");
- var eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".hea");
- if (decode)
- {
- paramBytes = Convert.FromBase64String(heaFile);
- eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".json");
- paramBytes = Convert.FromBase64String(jsonFile);
- eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".atr");
- paramBytes = Convert.FromBase64String(atrFile);
- eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
- if (datFile != null)
- {
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".dat");
- paramBytes = Convert.FromBase64String(datFile);
- eventBlobAnnotations.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- }
- else
- {
- eventBlobAnnotations.UploadText(heaFile);
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".json");
- eventBlobAnnotations.UploadText(jsonFile);
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".atr");
- var streamContentsAtr = _atrFile.InputStream;
- streamContentsAtr.Position = 0;
- await eventBlobAnnotations.UploadFromStreamAsync(streamContentsAtr);
- _datFile = HttpContext.Current.Request.Files.Get("event_dat");
- if (_datFile != null)
- {
- var streamContentsDat = _datFile.InputStream;
- eventBlobAnnotations = blobContainer.GetBlockBlobReference(fileNameAnnotations + ".dat");
- streamContentsDat.Position = 0;
- await eventBlobAnnotations.UploadFromStreamAsync(streamContentsDat);
- }
- }
- //Create a Queue Message
- CloudQueueClient queueClient = context.QueueClient;
- // Retrieve a reference to a queue
- CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
- // Create the queue if it doesn't already exist
- queue.CreateIfNotExists();
- // Create a message and add it to the queue.
- CloudQueueMessage queueMessage = new CloudQueueMessage(fileNameAnnotations);
- queue.AddMessage(queueMessage);
- }
- else
- {
- JustAnnotations = false;
- //If we were requesting data, increment actions count when data is received.
- if (EventTypeString.Equals("Request"))
- {
- using (var DBcontext = new LifeSenseDBEntities())
- {
- var studyId = Functions.GetStudyId(device_serial.Split('_')[0]);
- var study = DBcontext.Studies.FirstOrDefault(o => o.Id == studyId);
- int actionCount = study.ActionsCount.Value;
- actionCount++;
- study.ActionsCount = actionCount;
- DBcontext.Entry(study).CurrentValues.SetValues(study);
- DBcontext.SaveChanges();
- }
- }
- }
- }
- if(!JustAnnotations)
- {
- _datFile = HttpContext.Current.Request.Files.Get("event_dat");
- Stream streamContentsDat = null;
- if (_datFile != null)
- {
- streamContentsDat = _datFile.InputStream;
- datFile = new StreamReader(_datFile.InputStream).ReadToEnd();
- }
- _atrFile = HttpContext.Current.Request.Files.Get("event_atr");
- var streamContentsAtr = _atrFile.InputStream;
- //Get the studyId of the device running
- var studyId = Functions.GetStudyId(device_serial.Split('_')[0]);
- // var studyStarted = Functions.CheckIfStudyStarted(studyId);
- string fileName = "";
- //if (!studyStarted)
- //{
- // studyId = 0;
- //}
- //Upload the header
- 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");
- fileName = studyId + "/ecg/" + folderName + "/" + folderName;
- // Create the blob client.
- blobContainer = context.BlobClient.GetContainerReference("studies");
- var eventBlob = blobContainer.GetBlockBlobReference(fileName + ".hea");
- if (decode)
- {
- paramBytes = Convert.FromBase64String(heaFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- else
- {
- eventBlob.UploadText(heaFile);
- }
- //Upload the json if it exists
- if (jsonFile != null)
- {
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".json");
- if (decode)
- {
- paramBytes = Convert.FromBase64String(jsonFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- else
- {
- eventBlob.UploadText(jsonFile);
- }
- }
- //Upload the atr file if it exists
- if (atrFile != null)
- {
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".atr");
- if (decode)
- {
- paramBytes = Convert.FromBase64String(atrFile);
- eventBlob.UploadText(Encoding.UTF8.GetString(paramBytes));
- }
- else
- {
- streamContentsAtr.Position = 0;
- await eventBlob.UploadFromStreamAsync(streamContentsAtr);
- }
- }
- //Upload the data file
- if (datFile != null)
- {
- eventBlob = blobContainer.GetBlockBlobReference(fileName + ".dat");
- if (decode)
- {
- paramBytes = Convert.FromBase64String(datFile);
- eventBlob.UploadFromByteArray(paramBytes, 0, paramBytes.Length, null);
- }
- else
- {
- streamContentsDat.Position = 0;
- await eventBlob.UploadFromStreamAsync(streamContentsDat);
- }
- }
- //Create a Queue Message
- CloudQueueClient queueClient = context.QueueClient;
- // Retrieve a reference to a queue
- CloudQueue queue = queueClient.GetQueueReference("wirelessevent");
- // Create the queue if it doesn't already exist
- queue.CreateIfNotExists();
- // Create a message and add it to the queue.
- CloudQueueMessage queueMessage = new CloudQueueMessage(fileName);
- queue.AddMessage(queueMessage);
- }
- //Returned Message
- HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
- string yourJson = "{\"result\":\"Success\"}";
- message.Content = new StringContent(yourJson);
- return message;
- // return yourJson;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement