public ActionResult GetProfilePicture(int personId)
        {
            try
            {
                var person = this.db.Persons.First(p => p.Id == personId);

                if (person.PictureBlobName != null)
                {
                    var storageManager = new WindowsAzureBlobStorageManager();
                    var picture = storageManager.DownloadFileFromStorage(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, person.PictureBlobName);
                    return this.File(picture, "image/png", person.PictureBlobName);
                }

                // if the file does not exist, return a male or female image
                var pictureResource =
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                        person.Gender == (int)TypeGender.Male
                            ? "CerebelloWebRole.Resources.Male-Default-Profile.jpg"
                            : "CerebelloWebRole.Resources.Female-Default-Profile.jpg");

                return pictureResource != null ? this.File(pictureResource, "image/jpg") : null;
            }
            catch (Exception ex)
            {
                var pictureResource = Assembly.GetExecutingAssembly().GetManifestResourceStream("CerebelloWebRole.Resources.Male-Default-Profile.jpg");
                return pictureResource != null ? this.File(pictureResource, "image/jpg") : null;
            }
        }
        public JsonResult PostPicture(CameraWindowViewModel formModel)
        {
            try
            {
                var postedData = this.Request["image"];
                if (string.IsNullOrEmpty(postedData))
                    throw new Exception("Could not find the uploaded image");

                var data = postedData.Substring(22);
                var bytes = Convert.FromBase64String(data);
                var bytesStream = new MemoryStream(bytes);
                bytesStream.Seek(0, SeekOrigin.Begin);

                var tempFileName = Guid.NewGuid().ToString().ToLower();

                var storageManager = new WindowsAzureBlobStorageManager();
                storageManager.UploadFileToStorage(bytesStream, Constants.AZURE_STORAGE_TEMP_FILES_CONTAINER_NAME, tempFileName);

                return this.Json(
                    new
                        {
                            success = true,
                            fileName = tempFileName,
                            containerName = Constants.AZURE_STORAGE_TEMP_FILES_CONTAINER_NAME
                        });
            }
            catch (Exception ex)
            {
                return this.Json(
                    new
                        {
                            success = false,
                            message = ex.Message
                        });
            }
        }
        public ActionResult DeleteProfilePicture(int personId)
        {
            var person = this.db.Persons.FirstOrDefault(p => p.Id == personId);

            try
            {
                if (person != null && person.PictureBlobName != null)
                {
                    var storageManager = new WindowsAzureBlobStorageManager();
                    storageManager.DeleteFileFromStorage(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, person.PictureBlobName);
                    person.PictureBlobName = null;
                    this.db.SaveChanges();
                    return this.Json(
                        new
                            {
                                success = true
                            },
                        JsonRequestBehavior.AllowGet);
                }
                return this.Json(
                        new
                        {
                            success = true
                        },
                        JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(
                    new
                    {
                        success = false,
                        message = ex.Message
                    }, JsonRequestBehavior.AllowGet);
            }
        }
        public static MemoryStream GeneratePatientBackup([NotNull] CerebelloEntitiesAccessFilterWrapper db,
                                                         [NotNull] Patient patient)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }
            if (patient == null)
            {
                throw new ArgumentNullException("patient");
            }

            var zipMemoryStream = new MemoryStream();

            using (var patientZip = new ZipFile())
            {
                var storageManager = new WindowsAzureBlobStorageManager();

                // add the patient history as pdf
                var pdf = ReportController.ExportPatientsPdf(patient.Id, db, patient.Practice, patient.Doctor);
                patientZip.AddEntry(string.Format("{0} - Histórico.pdf", patient.Person.FullName), pdf);

                // if the person has a picture, add it to the backup
                if (patient.Person.PictureBlobName != null)
                {
                    var picture = storageManager.DownloadFileFromStorage(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, patient.Person.PictureBlobName);
                    patientZip.AddEntry(string.Format("{0} - Perfil.png", patient.Person.FullName), picture);
                }

                // if the person has files, add them to the backup
                var patientFiles = db.PatientFiles.Where(pf => pf.PatientId == patient.Id).ToList();
                if (patientFiles.Any())
                {
                    using (var patientFilesZip = new ZipFile())
                    {
                        var patientFilesZipMemoryStream = new MemoryStream();
                        foreach (var patientFile in patientFiles)
                        {
                            var fileStream = storageManager.DownloadFileFromStorage(
                                patientFile.FileMetadata.ContainerName, patientFile.FileMetadata.BlobName);
                            var fileName = patientFile.FileMetadata.SourceFileName;
                            for (var i = 2;; i++)
                            {
                                if (patientFilesZip.ContainsEntry(fileName))
                                {
                                    fileName = Path.GetFileNameWithoutExtension(fileName) + " " + i + Path.GetExtension(fileName);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            patientFilesZip.AddEntry(fileName, fileStream);
                        }

                        patientFilesZip.Save(patientFilesZipMemoryStream);
                        patientFilesZipMemoryStream.Seek(0, SeekOrigin.Begin);
                        patientZip.AddEntry(string.Format("{0} - Arquivos.zip", patient.Person.FullName), patientFilesZipMemoryStream);
                    }
                }

                patientZip.Save(zipMemoryStream);
            }

            zipMemoryStream.Seek(0, SeekOrigin.Begin);
            return(zipMemoryStream);
        }
Beispiel #5
0
        public static MemoryStream GeneratePatientBackup([NotNull] CerebelloEntitiesAccessFilterWrapper db,
                                                         [NotNull] Patient patient)
        {
            if (db == null) throw new ArgumentNullException("db");
            if (patient == null) throw new ArgumentNullException("patient");

            var zipMemoryStream = new MemoryStream();
            using (var patientZip = new ZipFile())
            {
                var storageManager = new WindowsAzureBlobStorageManager();

                // add the patient history as pdf
                var pdf = ReportController.ExportPatientsPdf(patient.Id, db, patient.Practice, patient.Doctor);
                patientZip.AddEntry(string.Format("{0} - Histórico.pdf", patient.Person.FullName), pdf);

                // if the person has a picture, add it to the backup
                if (patient.Person.PictureBlobName != null)
                {
                    var picture = storageManager.DownloadFileFromStorage(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, patient.Person.PictureBlobName);
                    patientZip.AddEntry(string.Format("{0} - Perfil.png", patient.Person.FullName), picture);
                }

                // if the person has files, add them to the backup
                var patientFiles = db.PatientFiles.Where(pf => pf.PatientId == patient.Id).ToList();
                if (patientFiles.Any())
                {
                    using (var patientFilesZip = new ZipFile())
                    {
                        var patientFilesZipMemoryStream = new MemoryStream();
                        foreach (var patientFile in patientFiles)
                        {
                            var fileStream = storageManager.DownloadFileFromStorage(
                                patientFile.FileMetadata.ContainerName, patientFile.FileMetadata.BlobName);
                            var fileName = patientFile.FileMetadata.SourceFileName;
                            for (var i = 2;; i++)
                            {
                                if (patientFilesZip.ContainsEntry(fileName))
                                {
                                    fileName = Path.GetFileNameWithoutExtension(fileName) + " " + i + Path.GetExtension(fileName);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            patientFilesZip.AddEntry(fileName, fileStream);
                        }

                        patientFilesZip.Save(patientFilesZipMemoryStream);
                        patientFilesZipMemoryStream.Seek(0, SeekOrigin.Begin);
                        patientZip.AddEntry(string.Format("{0} - Arquivos.zip", patient.Person.FullName), patientFilesZipMemoryStream);
                    }
                }

                patientZip.Save(zipMemoryStream);
            }

            zipMemoryStream.Seek(0, SeekOrigin.Begin);
            return zipMemoryStream;
        }
        public ActionResult DownloadZipFile(int patientId)
        {
            var patient = this.db.Patients.First(p => p.Id == patientId);
            var zipMemoryStream = new MemoryStream();

            using (var zip = new ZipFile())
            {
                var patientFiles = this.db.PatientFiles.Where(pf => pf.PatientId == patientId).ToList();
                var storageManager = new WindowsAzureBlobStorageManager();

                foreach (var patientFile in patientFiles)
                {
                    var fileStream = storageManager.DownloadFileFromStorage(
                        patientFile.FileMetadata.ContainerName, patientFile.FileMetadata.BlobName);

                    zip.AddEntry(patientFile.FileMetadata.SourceFileName, fileStream);
                }
                zip.Save(zipMemoryStream);
            }

            zipMemoryStream.Seek(0, SeekOrigin.Begin);
            return this.File(
                zipMemoryStream,
                "application/zip",
                patient.Person.FullName + " - Arquivos - " + this.GetPracticeLocalNow().ToShortDateString() + ".zip");
        }
        public ActionResult DownloadAllPatientsZipFile()
        {
            var mainZipMemoryStream = new MemoryStream();

            // there will an outer zip file that will contain an inner
            // zip file for each patient that has files
            using (var outerZip = new ZipFile())
            {
                foreach (var patient in this.Doctor.Patients)
                {
                    // if the patient has no files, he's not going to be included
                    if (!patient.PatientFiles.Any())
                        continue;

                    var innerZipMemoryStream = new MemoryStream();
                    using (var innerZip = new ZipFile())
                    {
                        var storageManager = new WindowsAzureBlobStorageManager();

                        foreach (var patientFile in patient.PatientFiles)
                        {
                            try
                            {
                                var fileStream = storageManager.DownloadFileFromStorage(
                                    patientFile.FileMetadata.ContainerName, patientFile.FileMetadata.BlobName);

                                innerZip.AddEntry(patientFile.FileMetadata.SourceFileName, fileStream);
                            }
                            catch (Exception ex)
                            {
                                // in this case the file exists in the database but does not exist in the storage.
                                Trace.TraceError(ex.Message);
                            }
                        }

                        innerZip.Save(innerZipMemoryStream);
                    }

                    innerZipMemoryStream.Seek(0, SeekOrigin.Begin);
                    outerZip.AddEntry(patient.Person.FullName + ".zip", innerZipMemoryStream);
                }

                outerZip.Save(mainZipMemoryStream);
            }

            mainZipMemoryStream.Seek(0, SeekOrigin.Begin);
            return this.File(
                mainZipMemoryStream,
                "application/zip",
                this.Doctor.Users.ElementAt(0).Person.FullName + " - Arquivos dos pacientes - " +
                    this.GetPracticeLocalNow().ToShortDateString() + ".zip");
        }
Beispiel #8
0
        /// <summary>
        /// Runs the worker once to do the tests.
        /// </summary>
        public override void RunOnce()
        {
            // If this method is already running, then leave the already running alone, and return.
            // If it is not running, set the value os locker to 1 to indicate that now it is running.
            if (Interlocked.Exchange(ref locker, 1) != 0)
            {
                Trace.TraceInformation("TestWorker.RunOnce(): already running, exiting now.");
                return;
            }

            Trace.TraceInformation("TestWorker.RunOnce(): running service");

            var utcNow = this.GetUtcNow();
            using (var db = this.CreateNewCerebelloEntities())
            {
                // trying to save to the database
                Exception exSaveToDb = null;
                SPECIAL_Test dbObj = null;
                try
                {
                    var o = new SPECIAL_Test
                        {
                            CreatedOn = utcNow,
                        };

                    db.SPECIAL_Test.AddObject(o);

                    db.SaveChanges();

                    dbObj = o;
                }
                catch (Exception ex)
                {
                    exSaveToDb = ex;
                }

                if (exSaveToDb == null)
                    Trace.TraceInformation("TestWorker.RunOnce(): DB object saved");

                // trying to save a file in the storage
                Exception exSaveToStorage = null;
                try
                {
                    var storageManager = new WindowsAzureBlobStorageManager();
                    using (var stream = new MemoryStream(new byte[0]))
                        storageManager.UploadFileToStorage(
                            stream, "worker-test", string.Format("{0}", utcNow.ToString("yyyy'-'MM'-'dd hh'-'mm")));
                }
                catch (Exception ex)
                {
                    exSaveToStorage = ex;
                }

                if (exSaveToStorage == null)
                    Trace.TraceInformation("TestWorker.RunOnce(): blob saved to storage");

                // Sending e-mail about test status
                Exception exSendEmail = null;
                try
                {
                    var obj = new Dictionary<string, Exception>
                        {
                            { "exSaveToDb", exSaveToDb },
                            { "exSaveToStorage", exSaveToStorage },
                        };

                    var mailMessage = this.CreateEmailMessage("TestEmail", new MailAddress("*****@*****.**"), obj);
                    if (!this.TrySendEmail(mailMessage))
                        throw new Exception("Cannot send e-mail message.");
                }
                catch (Exception ex)
                {
                    exSendEmail = ex;
                }

                if (exSendEmail == null)
                    Trace.TraceInformation("TestWorker.RunOnce(): e-mail message sent");

                // Save result to storage
                var fileText = new StringBuilder(1000);
                fileText.AppendLine("File saved from TestWorker");

                if (exSaveToDb != null)
                {
                    fileText.AppendLine();
                    fileText.AppendLine("Save to DB failed: " + exSaveToDb.Message);
                }

                if (exSaveToStorage != null)
                {
                    fileText.AppendLine();
                    fileText.AppendLine("Save to Storage failed: " + exSaveToStorage.Message);
                }

                if (exSendEmail != null)
                {
                    fileText.AppendLine();
                    fileText.AppendLine("Send e-mail failed: " + exSendEmail.Message);
                }

                if (exSaveToStorage == null)
                    try
                    {
                        var storageManager = new WindowsAzureBlobStorageManager();
                        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(fileText.ToString())))
                            storageManager.UploadFileToStorage(
                                stream, "worker-test", string.Format("{0}", utcNow.ToString("yyyy'-'MM'-'dd hh'-'mm")));
                    }
                    catch
                    {
                    }

                // Save result to db
                if (exSaveToDb == null)
                    try
                    {
                        if (dbObj != null)
                        {
                            dbObj.Value = fileText.ToString();
                            db.SaveChanges();
                        }
                    }
                    catch
                    {
                    }
            }

            // setting locker value to 0
            if (Interlocked.Exchange(ref locker, 0) != 1)
                throw new Exception("The value of locker should be 1 before setting it to 0.");
        }
        public JsonResult Delete(int id)
        {
            try
            {
                var patient = this.db.Patients.First(m => m.Id == id);

                // delete anamneses manually
                var anamneses = patient.Anamneses.ToList();
                while (anamneses.Any())
                {
                    var anamnese = anamneses.First();
                    this.db.Anamnese.DeleteObject(anamnese);
                    anamneses.Remove(anamnese);
                }

                // delete diagnostic hipotheses manually
                var diagnosticHypotheses = patient.DiagnosticHypotheses.ToList();
                while (diagnosticHypotheses.Any())
                {
                    var diagnosticHypothesis = diagnosticHypotheses.First();
                    this.db.DiagnosticHypotheses.DeleteObject(diagnosticHypothesis);
                    diagnosticHypotheses.Remove(diagnosticHypothesis);
                }

                // delete receipts manually
                var receipts = patient.Receipts.ToList();
                while (receipts.Any())
                {
                    var receipt = receipts.First();
                    this.db.Receipts.DeleteObject(receipt);
                    receipts.Remove(receipt);
                }

                // delete physical exams requests manually
                var physicalExams = patient.PhysicalExaminations.ToList();
                while (physicalExams.Any())
                {
                    var physicalExam = physicalExams.First();
                    this.db.PhysicalExaminations.DeleteObject(physicalExam);
                    physicalExams.Remove(physicalExam);
                }

                // delete exam requests manually
                var examRequests = patient.ExaminationRequests.ToList();
                while (examRequests.Any())
                {
                    var examRequest = examRequests.First();
                    this.db.ExaminationRequests.DeleteObject(examRequest);
                    examRequests.Remove(examRequest);
                }

                // delete exam results manually
                var examResults = patient.ExaminationResults.ToList();
                while (examResults.Any())
                {
                    var examResult = examResults.First();
                    this.db.ExaminationResults.DeleteObject(examResult);
                    examResults.Remove(examResult);
                }

                // delete medical certificates manually
                var certificates = patient.MedicalCertificates.ToList();
                while (certificates.Any())
                {
                    var certificate = certificates.First();

                    // deletes fields within the certificate manually
                    while (certificate.Fields.Any())
                    {
                        var field = certificate.Fields.First();
                        this.db.MedicalCertificateFields.DeleteObject(field);
                    }

                    this.db.MedicalCertificates.DeleteObject(certificate);
                    certificates.Remove(certificate);
                }

                // delete diagnosis manually
                var diagnosis = patient.Diagnoses.ToList();
                while (diagnosis.Any())
                {
                    var diag = diagnosis.First();
                    this.db.Diagnoses.DeleteObject(diag);
                    diagnosis.Remove(diag);
                }

                // delete appointments manually
                var appointments = patient.Appointments.ToList();
                while (appointments.Any())
                {
                    var appointment = appointments.First();
                    this.db.Appointments.DeleteObject(appointment);
                    appointments.Remove(appointment);
                }

                // delete files manually
                var patientFiles = patient.PatientFiles.ToList();
                while (patientFiles.Any())
                {
                    var patientFile = patientFiles.First();
                    var file = patientFile.FileMetadata;

                    var storage = new WindowsAzureBlobStorageManager();
                    storage.DeleteFileFromStorage(Constants.AZURE_STORAGE_PATIENT_FILES_CONTAINER_NAME, file.SourceFileName);

                    this.db.PatientFiles.DeleteObject(patientFile);
                    this.db.FileMetadatas.DeleteObject(file);

                    patientFiles.Remove(patientFile);
                }

                // delete file groups manually
                var patientFileGroups = patient.PatientFileGroups.ToList();
                while (patientFileGroups.Any())
                {
                    var patientFileGroup = patientFileGroups.First();
                    this.db.PatientFileGroups.DeleteObject(patientFileGroup);
                    patientFileGroups.Remove(patientFileGroup);
                }

                this.db.Patients.DeleteObject(patient);
                this.db.SaveChanges();
                return this.Json(new JsonDeleteMessage { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(new JsonDeleteMessage { success = false, text = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// Sets a person picture as the specified tempFileName.
        /// The tempFileName will be COPIED from the "temp" Azure Storage container name
        /// tempFileName can be deleted afterwards
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="tempFileName"></param>
        /// <returns></returns>
        public JsonResult TransferPersonPictureFromTempContainer(int personId, string tempFileName)
        {
            try
            {
                var person = this.db.Persons.First(p => p.Id == personId);
                var profilePictureBlobName = "profile_picture_" + personId;

                var sourceLocation = new BlobLocation(Constants.AZURE_STORAGE_TEMP_FILES_CONTAINER_NAME, tempFileName);
                var destinationLocation = new BlobLocation(Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, profilePictureBlobName);

                // download temp file
                var storageManager = new WindowsAzureBlobStorageManager();
                //var tempFile = storageManager.DownloadFileFromStorage(sourceLocation);

                // if person has a profile picture already, delete it
                if (person.PictureBlobName != null)
                    storageManager.DeleteFileFromStorage(destinationLocation);

                storageManager.CopyStoredFile(sourceLocation, destinationLocation);

                // upload downloaded temp file to person profile
                //storageManager.UploadFileToStorage(tempFile, Constants.PERSON_PROFILE_PICTURE_CONTAINER_NAME, profilePictureBlobName);
                person.PictureBlobName = profilePictureBlobName;

                // delete temp file
                storageManager.DeleteFileFromStorage(sourceLocation);

                // this controller shouldn't know about patients but.. it's the easiest way to do this now
                if (person.Patients.Any())
                    person.Patients.First().IsBackedUp = false;

                this.db.SaveChanges();

                return this.Json(
                    new
                    {
                        success = true
                    }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.Json(
                    new
                    {
                        success = false,
                        message = ex.Message
                    }, JsonRequestBehavior.AllowGet);
            }
        }