Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.WindowsAzure.Storage.Queue;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using QueueProcessor.DataObjects;
- using SironaFilesProcessor;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Net.Http;
- using System.Security.AccessControl;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms.DataVisualization.Charting;
- namespace QueueProcessor
- {
- class PhysionetEventParser
- {
- public static async Task ProcessFiles(String message)
- {
- bool AtrCorrupted = false;
- //Create a temp direcotry in the Web root path
- var tempGuid = Guid.NewGuid().ToString();
- var tempFolder = (Environment.GetEnvironmentVariable("WEBROOT_PATH") ?? @"C:/users/public") + "/" + tempGuid;
- //Download event files to local directory previously created
- var storageContext = new StorageContext();
- // Get and create the container
- var studiesContainer = storageContext.BlobClient.GetContainerReference("studies");
- studiesContainer.CreateIfNotExists();
- Directory.CreateDirectory(tempFolder);
- var studyId = int.Parse(message.Split('_')[1]);
- //var tryingBlob = studiesContainer.GetAppendBlobReference(studyId + "/queuelog.txt");
- //if (!await tryingBlob.ExistsAsync())
- //{
- // await tryingBlob.CreateOrReplaceAsync();
- //}
- //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, ("Before Try: " + message)) + Environment.NewLine)))
- //{
- // await tryingBlob.AppendBlockAsync(ms);
- //}
- var rawFileName = message.Split('/')[message.Split('/').Length - 1];
- var blobName = message;
- try
- {
- #region Donwloading files from blobs to local directory
- var blob = studiesContainer.GetBlockBlobReference(blobName + ".hea");
- if (blob.Exists())
- {
- await blob.DownloadToFileAsync(tempFolder + "/" + rawFileName + ".hea", FileMode.OpenOrCreate);
- }
- blob = studiesContainer.GetBlockBlobReference(blobName + ".json");
- if (blob.Exists())
- {
- await blob.DownloadToFileAsync(tempFolder + "/" + rawFileName + ".json", FileMode.OpenOrCreate);
- }
- blob = studiesContainer.GetBlockBlobReference(blobName + ".dat");
- if (blob.Exists())
- {
- await blob.DownloadToFileAsync(tempFolder + "/" + rawFileName + ".dat", FileMode.OpenOrCreate);
- }
- blob = studiesContainer.GetBlockBlobReference(blobName + ".atr");
- if (blob.Exists())
- {
- await blob.DownloadToFileAsync(tempFolder + "/" + rawFileName + ".atr", FileMode.OpenOrCreate);
- }
- #endregion
- #region Processing Files
- //To check if the device and the study are valid here before processing any data
- var deviceSN = rawFileName.Split('_')[0];
- TimeSpan UTCValue = new TimeSpan();
- using (var context = new LifeSenseDBEntities())
- {
- var device = context.Devices.FirstOrDefault(o => o.SerialNumber == deviceSN && (o.Deleted == null || o.Deleted != true));
- if (device != null)
- {
- //Get the running or started study attached to the device
- var study = context.Studies.FirstOrDefault(o => o.DeviceId == device.Id && o.StatusId != 3);
- if (study != null)
- {
- study.LastActivity = DateTime.UtcNow;
- var recordName = rawFileName;
- //Parse the JSON file in order to map the event to its study and save it in the db
- //var jsonText = File.ReadAllText(tempFolderPath + "/" + fileName + "/" + recordName + ".json");
- //JObject jSonObject = JObject.Parse(jsonText);
- //JObject deviceInfo = (JObject)jSonObject["Device"];
- ////This field is called device ID by the manufacturer, though it refers to serial number in our number
- //var deviceId = (string)deviceInfo["Device ID"];
- //JObject patientInfo = (JObject)jSonObject["Patient"];
- ////PatientId on the mobile App is the Study ID in CloudBeat system
- //var patientId = (string)patientInfo["Patient ID"];
- //var patientFirstName = (string)patientInfo["Patient First Name"];
- //var patientMiddleName = (string)patientInfo["Patient Middle Initial"];
- //var patientLastName = (string)patientInfo["Patient Last Name"];
- //var patientPhysicianName = (string)patientInfo["Physician Name"];
- //JObject timeInfo = (JObject)jSonObject["Time"];
- //var procedureStartTime = (string)timeInfo["Procedure Start Time"];
- //var stripStartTime = (string)timeInfo["Strip Start Time"];
- //var stripLength = (string)timeInfo["Strip Length"];
- //var transmitTime = (string)timeInfo["Transmit Time"];
- //Parse the header file
- string[] lines = System.IO.File.ReadAllLines(tempFolder + "/" + recordName + ".hea");
- //Get Record Line Data (first line)
- var recordLineParams = lines[0].Split(' ');
- var recordNameInHeader = recordLineParams[0];
- var numberOfSignals = recordLineParams[1];
- int samplingFrequency = 250;
- int.TryParse(recordLineParams[2], out samplingFrequency);
- var numberOfSamplesPerSignal = recordLineParams[3]; //If it is zero or missing, the number of samples is unspecified
- var baseTime = recordLineParams[4]; //It gives the time of day that corresponds to the beginning of the record, in HH:MM:SS format
- var baseDate = recordLineParams[5]; //It contains the date that corresponds to the beginning of the record, in DD/MM/YYYY format
- var gain = 102.4;
- if (int.Parse(numberOfSignals) >= 1)
- {
- var firstSignaleLine = lines[1];
- var firstSignalLineParts = firstSignaleLine.Split(' ');
- if (firstSignalLineParts.Length > 2)
- {
- var success = Double.TryParse(firstSignalLineParts[2], out gain);
- if (!success)
- {
- gain = 102.4;
- }
- }
- }
- //Parsing the json file to get the eventtype
- string jsonFile = File.ReadAllText(tempFolder + "/" + recordName + ".json");
- string eventType = "";
- string StripLength = "";
- DateTime StripDate = new DateTime();
- if (jsonFile != null)
- {
- JObject Body = JsonConvert.DeserializeObject<JObject>(jsonFile, new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None });
- JObject timeInfo = (JObject)Body["Time"];
- eventType = (string)timeInfo["Event type"];
- var StripStartTime = (string)timeInfo["Strip Start Time"];
- StripLength = (string)timeInfo["Strip Length"];
- var dateTimeOffset = DateTimeOffset.Parse(StripStartTime, null);
- StripDate = dateTimeOffset.DateTime;
- UTCValue = dateTimeOffset.Offset;
- }
- /* string eventType = "Undefined";
- var commentsLine = "";
- if (lines.Length > 1 + int.Parse(numberOfSignals))
- {
- commentsLine = lines[1 + int.Parse(numberOfSignals)].ToLower();
- }
- if (commentsLine.Contains("manual"))
- {
- eventType = "Patient Triggered";
- }
- else if (commentsLine.Contains("automatic"))
- {
- var evType = commentsLine.Replace(" ", "").Split('-')[1].ToLower();
- var eventsMapper = context.PhysionetEventMappers.FirstOrDefault(o => o.DeviceEventType.ToLower() == evType);
- if (eventsMapper != null)
- {
- eventType = context.EventsTypes.FirstOrDefault(o => o.Id == eventsMapper.CBEventTypeId).Description;
- }
- else
- {
- eventType = "Undefined";
- }
- }
- */
- //Name, Type and Description will be the same
- switch (eventType)
- {
- case "Request":
- eventType = "Server Data Request";
- break;
- case "Automatic - BRADY":
- eventType = "Bradycardia";
- break;
- case "Automatic - TACHY":
- eventType = "Tachycardia";
- break;
- case "Automatic - PAUSE":
- eventType = "Pause Event";
- break;
- case "Manual":
- eventType = "Patient Triggered";
- break;
- case "Automatic - ARRHYTHMIA_AF":
- eventType = "Atrial Fibrillation";
- break;
- default:
- break;
- }
- if (eventType != "Server Data Request")
- {
- var newEvent = new Event();
- newEvent.StudyId = study.Id;
- newEvent.Name = eventType;
- newEvent.Type = eventType;
- newEvent.Description = eventType;
- //Parse the data file to convert it into CSV and store at the right place according to the study id.
- //Note here that for the time this parser has created, the signals data must be in the same .dat file
- SByteParser.ParseSironaECG(tempFolder + "/" + recordName + ".dat", numberOfSignals);
- //ToDo: Change the type, name and description
- if (File.Exists(tempFolder + "/" + recordName + ".atr"))
- {
- SByteParser.ParseSironaAnnotation(tempFolder + "/" + recordName + ".atr");
- }
- //var eventMonitorSettings = context.EventMonitorSettings.FirstOrDefault(o => o.StudyId == study.Id);
- //if (eventMonitorSettings != null)
- //{
- //}
- //else
- //{
- // newEvent.EventOccurredAtSample = 0;
- //}
- //The default number of samples is the worth of 3 minutes
- int numberofsamples = samplingFrequency * int.Parse(StripLength);
- //int.TryParse(numberOfSamplesPerSignal, out numberofsamples);
- //If we have 1.5 minutes to get NumberOfECGFiles = 2
- newEvent.NumberOfECGFiles = (int)Math.Ceiling((double)numberofsamples / (60 * samplingFrequency));
- if (device.DeviceTypeId == 6)
- {
- //Get the Pre and Post defined in the header
- //They are set in seconds, so change time to samples to know when the event occured
- string[] PrePost = lines[int.Parse(numberOfSignals) + 2].Split(' ');
- var Pre = PrePost[2];
- var Post = PrePost[4];
- var PreInSamples = int.Parse(Pre) * samplingFrequency;
- var PostInSamples = int.Parse(Post) * samplingFrequency;
- var eventOccuredAtSample = PreInSamples;
- newEvent.EventOccurredAtSample = eventOccuredAtSample;
- }
- else
- {
- var eventOccuredAtSample = (int)(numberofsamples / 2);
- newEvent.EventOccurredAtSample = eventOccuredAtSample; //Pretrigger and Postrigger are in seconds, the eventOccuredfAtSample is in number of samples
- }
- //Set the acitivity level and symptoms to 0 since they're not supported in Sirona
- newEvent.PatientActivityLevel = 0;
- newEvent.PatientSymptom = 0;
- //Set the AmplitudeMultiplier value in our DB which is the inverse of ADC gain for Sirona
- newEvent.AmplitudeMultiplier = 1 / gain;
- var patient = context.Patients.FirstOrDefault(o => o.Id == study.PatientId);
- var baseTimeDetails = baseTime.Split(':');
- var baseDateDetails = baseDate.Split('/');
- var UTCHoursPart = UTCValue.Hours;
- var UTCMinutesPart = UTCValue.Minutes;
- var UTCMinutes = UTCHoursPart * 60 + UTCMinutesPart;
- //Adding the start time of the event in UTC, because in CloudBeat Database it's all in UTC
- var startTime = StripDate.AddMinutes(-UTCMinutes);
- newEvent.StartTime = startTime;
- newEvent.EndTime = startTime.AddSeconds(numberofsamples / samplingFrequency);
- newEvent.MinutesFromUTC = UTCMinutes;
- if (context.Events.Any(x => x.StudyId == studyId && x.Type == eventType && x.StartTime == startTime))
- {
- newEvent = context.Events.FirstOrDefault(x => x.StudyId == studyId && x.Type == eventType && x.StartTime == startTime);
- }
- else
- {
- context.Events.Add(newEvent);
- context.SaveChanges();
- }
- //Save the annotations in a CSV format
- if (File.Exists(tempFolder + "/" + recordName + ".atr.tab"))
- {
- Utils.ConvertFromTabToCSV(tempFolder + "/" + recordName + ".atr.tab", tempFolder + "/" + newEvent.Id + "_ann.csv", 0, true);
- }
- // convert the output ECG file from tab format to CSV format
- Utils.ConvertFromTabToCSV(tempFolder + "/" + recordName + ".dat.tab", tempFolder + "/" + newEvent.Id + ".csv", int.Parse(numberOfSignals), false);
- if (newEvent.NumberOfECGFiles == 0)
- {
- var csvFile = File.ReadAllLines(tempFolder + "/" + newEvent.Id + ".csv");
- newEvent.NumberOfECGFiles = (int)(csvFile.Length / (60 * samplingFrequency));
- }
- if (newEvent.EventOccurredAtSample > newEvent.NumberOfECGFiles * 60 * samplingFrequency)
- {
- newEvent.EventOccurredAtSample = (newEvent.NumberOfECGFiles * 60 * samplingFrequency) / 2;
- }
- //Make the eventOccurredAtSample related to the minute in the middle and not the first minute
- if (studyId < 150)
- {
- newEvent.EventOccurredAtSample = newEvent.EventOccurredAtSample - 60 * samplingFrequency;
- Utils.CreatePreviewChart(studyId, newEvent.Id, tempFolder, (int)newEvent.NumberOfECGFiles, (int)newEvent.EventOccurredAtSample + 60 * samplingFrequency, (double)newEvent.AmplitudeMultiplier, samplingFrequency);
- }
- else
- {
- if (newEvent.EventOccurredAtSample < 0)
- {
- newEvent.EventOccurredAtSample = 0;
- }
- //Create image for triage
- Utils.CreatePreviewChart(studyId, newEvent.Id, tempFolder, (int)newEvent.NumberOfECGFiles, (int)newEvent.EventOccurredAtSample, (double)newEvent.AmplitudeMultiplier, samplingFrequency);
- }
- //Create image for event control
- Utils.CreateOverviewChart(studyId, newEvent.Id, newEvent.StartTime.Value, (int)newEvent.NumberOfECGFiles, (int)newEvent.EventOccurredAtSample, samplingFrequency, (double)newEvent.AmplitudeMultiplier, tempFolder);
- //Upload ECG CSV, annotations CSV and images to the blob
- var outputBlob = study.Id + "/ecg";
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + ".csv");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + ".csv");
- if (File.Exists(tempFolder + "/" + recordName + ".atr.tab"))
- {
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + "_ann.csv");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + "_ann.csv");
- }
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + ".gif");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + ".gif");
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + "-overview.gif");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + "-overview.gif");
- //Label the event as ready
- newEvent.Ready = true;
- context.SaveChanges();
- //////////////SAP TRANSMISSION API CALL///////////////////
- var provider = context.Users.FirstOrDefault(o => o.Id == study.ProviderId);
- if (device.CompanyId == 12)//TODO replace with actual company ID
- {
- var addressLine2Parts = (!string.IsNullOrEmpty(patient.AddressLine2)) ? Cipher.Decrypt(patient.AddressLine2, true).Split(',') : new string[0];
- var orderCreate = new OrderCreate(); //Strongly Typed JSON Object
- var header = new Header
- {
- CreationTimeStamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff"),//TIMESTAMP in UTC
- Identifier = "TRANS"//From JSON
- };
- orderCreate.Header = header;
- var medicalCenter = patient.MedicalCenter;
- var orderLineItemLp = new OrderLineItemLp
- {
- MaterialNum = (!string.IsNullOrEmpty(device.Notes)) ? device.Notes : "", //TODO: Change it when agreed where to put it
- ItemSerialLp = new ItemSerialLp
- {
- Serial = device.SerialNumber,
- PickQty = "1",
- ItemUoM = "PC"
- }
- };
- var orderHeader = new OrderHeader
- {
- PhysicianName = provider.LastName + ", " + provider.LastName,
- PhyNPINumber = "",//NOT PRESENT
- PatientName = Cipher.Decrypt(patient.LastName, true) + ", " + Cipher.Decrypt(patient.LastName, true),//Patient Name
- EnrollmentID = study.Id.ToString(),
- ShipTo = new ShipTo
- {
- ShipToID = medicalCenter.Email,//SHIPTO = MEDICAL CENTER
- AdrFName = medicalCenter.Name
- },
- OrderLineItemLp = orderLineItemLp
- };
- orderCreate.OrderHeader = orderHeader;
- RootObject rootObject = new RootObject
- {
- OrderCreate = orderCreate
- };
- Functions.PingSAPForNewTransmission(rootObject);
- }
- //////////////END SAP TRANSMISSION API CALL///////////////////
- //Call the webservice to notify the users
- var parameters = "{'eventID':" + newEvent.Id + "}";
- var httpClient = new HttpClient();
- var content = new StringContent(parameters, Encoding.UTF8, "application/json");
- var url = Utils.NotificationsURL + @"/User/Services/WebServices.asmx/SendNotifications";
- httpClient.PostAsync(url, content).Wait();
- }
- else
- {
- //ToDo: Change the type, name and description
- if (File.Exists(tempFolder + "/" + recordName + ".atr"))
- {
- SByteParser.ParseSironaAnnotation(tempFolder + "/" + recordName + ".atr");
- }
- //Save the annotations in a CSV format
- if (File.Exists(tempFolder + "/" + recordName + ".atr.tab"))
- {
- Utils.ConvertFromTabToCSV(tempFolder + "/" + recordName + ".atr.tab", tempFolder + "/TheOriginal_ann.csv", 0, true);
- }
- SByteParser.ParseSironaECG(tempFolder + "/" + recordName + ".dat", numberOfSignals);
- // convert the output ECG file from tab format to CSV format
- Utils.ConvertFromTabToCSV(tempFolder + "/" + recordName + ".dat.tab", tempFolder + "/TheOriginal.csv", int.Parse(numberOfSignals), false);
- string[] TheOriginalDat = File.ReadAllLines(tempFolder + "/TheOriginal.csv");
- string[] TheOriginalAtr = File.ReadAllLines(tempFolder + "/TheOriginal_ann.csv");
- int numberofsamples = samplingFrequency * int.Parse(StripLength);
- int NumberOfECGFiles = (int)Math.Ceiling((double)numberofsamples / (60 * samplingFrequency));
- int samplesInOneMinute = 60 * samplingFrequency;
- //Array that will hold values of the current temporary part of the strip (1 minute)
- string[] TempDat = new string[samplesInOneMinute];
- string[] TempAtr = new string[TheOriginalAtr.Length];
- int fromLine = 0;
- int toLine = 0;
- for (int i = 0; i < NumberOfECGFiles; i++)
- {
- fromLine = toLine;
- toLine = 0;
- //To account for the last seconds after the before last minute
- int samplesToCopy = samplesInOneMinute;
- if( i == NumberOfECGFiles - 1)
- {
- samplesToCopy = TheOriginalDat.Length - samplesInOneMinute * i;
- }
- TempDat = new string[samplesToCopy];
- Array.Copy(TheOriginalDat, i * samplesInOneMinute, TempDat, 0, samplesToCopy);
- TempAtr = new string[TheOriginalAtr.Length];
- try
- {
- foreach (var line in TheOriginalAtr)
- {
- string[] columns = line.Split(',');
- int CurrentMinute = (int)(int.Parse(columns[0]) / (60 * samplingFrequency));
- if (CurrentMinute > i)
- {
- break;
- }
- toLine++;
- }
- Array.Copy(TheOriginalAtr, fromLine, TempAtr, 0, (toLine - fromLine));
- TempAtr = TempAtr.Where(o => o != "").ToArray();
- TempAtr = TempAtr.Where(o => o != null).ToArray();
- }
- catch (Exception ex)
- {
- AtrCorrupted = true;
- 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(message + ":" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine)))
- {
- errorFile.AppendBlock(ms);
- }
- }
- var newEvent = new Event();
- newEvent.StudyId = study.Id;
- newEvent.Name = eventType;
- newEvent.Type = eventType;
- if (i == 0)
- {
- newEvent.Description = "DDR Start";
- }
- else if(i == NumberOfECGFiles - 1)
- {
- newEvent.Description = "DDR End";
- }
- else
- {
- newEvent.Description = "DDR Cont.";
- }
- //Set the acitivity level and symptoms to 0 since they're not supported in Sirona
- newEvent.PatientActivityLevel = 0;
- newEvent.PatientSymptom = 0;
- //Set the AmplitudeMultiplier value in our DB which is the inverse of ADC gain for Sirona
- newEvent.AmplitudeMultiplier = 1 / gain;
- var UTCHoursPart = UTCValue.Hours;
- var UTCMinutesPart = UTCValue.Minutes;
- var UTCMinutes = UTCHoursPart * 60 + UTCMinutesPart;
- //Adding the start time of the event in UTC, because in CloudBeat Database it's all in UTC
- var startTime = StripDate.AddMinutes(-UTCMinutes);
- newEvent.StartTime = startTime.AddSeconds((i * samplesInOneMinute)/samplingFrequency);
- newEvent.EndTime = startTime.AddSeconds((i * samplesInOneMinute + samplesToCopy)/samplingFrequency);
- newEvent.EventOccurredAtSample = samplesToCopy / 2;
- newEvent.MinutesFromUTC = UTCMinutes;
- if (context.Events.Any(x => x.StudyId == studyId && x.Type == eventType && x.StartTime == newEvent.StartTime && x.Description == newEvent.Description))
- {
- newEvent = context.Events.FirstOrDefault(x => x.StudyId == studyId && x.Type == eventType && x.StartTime == newEvent.StartTime && x.Description == newEvent.Description);
- }
- else
- {
- context.Events.Add(newEvent);
- context.SaveChanges();
- }
- File.WriteAllLines(tempFolder + "/" + newEvent.Id + ".csv", TempDat);
- if (!AtrCorrupted)
- {
- File.WriteAllLines(tempFolder + "/" + newEvent.Id + "_ann.csv", TempAtr);
- }
- //Create image for triage
- Utils.CreatePreviewChart(studyId, newEvent.Id, tempFolder, 1, (int)(samplesToCopy/2), (double)newEvent.AmplitudeMultiplier, samplingFrequency);
- //Create image for event control
- Utils.CreateOverviewChart(studyId, newEvent.Id, newEvent.StartTime.Value, 1, (int)(samplesToCopy / 2), samplingFrequency, (double)newEvent.AmplitudeMultiplier, tempFolder);
- //Upload ECG CSV, annotations CSV and images to the blob
- var outputBlob = study.Id + "/ecg";
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + ".csv");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + ".csv");
- if (!AtrCorrupted)
- {
- if (File.Exists(tempFolder + "/" + recordName + ".atr.tab"))
- {
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + "_ann.csv");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + "_ann.csv");
- }
- }
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + ".gif");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + ".gif");
- blob = studiesContainer.GetBlockBlobReference(outputBlob + @"/" + newEvent.Id + "-overview.gif");
- blob.UploadFromFile(tempFolder + "/" + newEvent.Id + "-overview.gif");
- //Label the event as ready
- newEvent.Ready = true;
- context.SaveChanges();
- }
- }
- }
- }
- }
- //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, ("After Try: " + message)) + Environment.NewLine)))
- //{
- // await tryingBlob.AppendBlockAsync(ms);
- //}
- #endregion
- }
- catch (Exception ex)
- {
- 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(message + ":" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine)))
- {
- errorFile.AppendBlock(ms);
- }
- return;
- }
- //Delete the temp file created by this instance
- Utils.DeleteDirectory(tempFolder);
- }
- unsafe static public Boolean ParseSironaECG(string filePath, string numberOfSignals)
- {
- try
- {
- string myString = "";
- for (int i = 0; i < 255; i++) myString += " ";
- //get the byte array
- byte[] bytes = Encoding.ASCII.GetBytes(filePath);
- byte[] errbytes = Encoding.ASCII.GetBytes(myString);
- sbyte* sbFileName;
- sbyte* sbError;
- fixed (byte* ptr_bytes = &bytes[0])
- sbFileName = (sbyte*)ptr_bytes;
- fixed (byte* ptr_errbytes = &errbytes[0])
- sbError = (sbyte*)ptr_errbytes;
- // PhysionetParser.PhysionetParser.readSironaEcg(sbFileName);
- PhysionetParser.PhysionetParser.readSironaEcg(sbFileName, int.Parse(numberOfSignals));
- //Upload the parsed file to the blob
- var context = new StorageContext();
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement