public void SaveLeafletsInMedicinesJsonToDb(CerebelloEntities db, Action<int, int> progress = null) { var medicines = new JavaScriptSerializer() .Deserialize<List<MedicineRaw>>(File.ReadAllText("medicines.json")); SaveLeafletsToDb(db, medicines, progress); }
public CerebelloEntitiesAccessFilterWrapper([NotNull] CerebelloEntities innerDb) { if (innerDb == null) { throw new ArgumentNullException("innerDb"); } this.innerDb = innerDb; }
/// <summary> /// Generates notifications for new Medical Appointments /// </summary> private static void GenerateNotificationsForNewMedicalAppointments( [NotNull] CerebelloEntities db, DateTime referenceTime, [NotNull] ICollection <Tuple <Notification, object> > notificationsToBeDispatched) { if (db == null) { throw new ArgumentNullException("db"); } if (notificationsToBeDispatched == null) { throw new ArgumentNullException("notificationsToBeDispatched"); } // check for appointments that have to be notified var timeOffset = referenceTime.AddMinutes(10); var unnotifiedAppointments = db.Appointments.Where( a => !a.Notified && a.Type == (int)TypeAppointment.MedicalAppointment && a.Start >= referenceTime && a.Start < timeOffset).ToList(); foreach (var appointment in unnotifiedAppointments) { Debug.Assert(appointment.PatientId != null, "appointment.PatientId != null"); var medicalAppointmentData = new MedicalAppointmentNotificationData { PatientId = appointment.PatientId.Value, PatientName = appointment.Patient.Person.FullName, DoctorName = appointment.Patient.Doctor.Users.First().Person.FullName, DoctorId = appointment.Patient.DoctorId, AppointmentId = appointment.Id, Time = DateTimeHelper.GetFormattedTime( PracticeController.ConvertToLocalDateTime(appointment.Practice, appointment.Start)), PracticeIdentifier = appointment.Practice.UrlIdentifier, DoctorIdentifier = appointment.Doctor.UrlIdentifier }; var medicalAppointmentDataString = new JavaScriptSerializer().Serialize(medicalAppointmentData); // for each secretary, I need to create a new notification foreach (var user in appointment.Practice.Users.Where(user => user.Secretary != null)) { var newNotification = new Notification() { CreatedOn = referenceTime, IsClosed = false, UserToId = user.Id, Type = NotificationConstants.MEDICAL_APPOINTMENT_NOTIFICATION_TYPE, PracticeId = appointment.PracticeId, Data = medicalAppointmentDataString }; user.Notifications.Add(newNotification); notificationsToBeDispatched.Add(new Tuple <Notification, object>(newNotification, medicalAppointmentData)); } appointment.Notified = true; } db.SaveChanges(); }
public static void CreateNotificationsJob() { ThreadPool.QueueUserWorkItem(state => { try { while (true) { Trace.TraceInformation("NotificationsHelper.CreateNotificationsJob(): Service in execution"); using (var db = new CerebelloEntities()) { // this TUPLE is: Notification AND NotificationData (which is SPECIFIC for each type of notification) var notificationsToBeDispatched = new List <Tuple <Notification, object> >(); // events should be GREATER OR EQUAL to (referenceDate) and LESSER than (referenceDate + offset) var referenceTime = DateTime.UtcNow; // check for new medical appointments try { GenerateNotificationsForNewMedicalAppointments(db, referenceTime, notificationsToBeDispatched); } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Could not generate notifications for medical appointments. Ex:" + ex.Message); } // check for generic appointments try { GenerateNotificationsForNewGenericAppointments(db, referenceTime, notificationsToBeDispatched); } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Could not generate notifications for generic appointments. Ex:" + ex.Message); } // dispatch notifications to the client NotificationsHub.BroadcastDbNotifications(notificationsToBeDispatched); } Thread.Sleep(5 * 60 * 1000); } } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Error in the notifications service. Ex:" + ex.Message); } }, null); }
public static void CreateNotificationsJob() { ThreadPool.QueueUserWorkItem(state => { try { while (true) { Trace.TraceInformation("NotificationsHelper.CreateNotificationsJob(): Service in execution"); using (var db = new CerebelloEntities()) { // this TUPLE is: Notification AND NotificationData (which is SPECIFIC for each type of notification) var notificationsToBeDispatched = new List<Tuple<Notification, object>>(); // events should be GREATER OR EQUAL to (referenceDate) and LESSER than (referenceDate + offset) var referenceTime = DateTime.UtcNow; // check for new medical appointments try { GenerateNotificationsForNewMedicalAppointments(db, referenceTime, notificationsToBeDispatched); } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Could not generate notifications for medical appointments. Ex:" + ex.Message); } // check for generic appointments try { GenerateNotificationsForNewGenericAppointments(db, referenceTime, notificationsToBeDispatched); } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Could not generate notifications for generic appointments. Ex:" + ex.Message); } // dispatch notifications to the client NotificationsHub.BroadcastDbNotifications(notificationsToBeDispatched); } Thread.Sleep(5 * 60 * 1000); } } catch (Exception ex) { Trace.TraceError("NotificationsHelper.CreateNotificationsJob(): Error in the notifications service. Ex:" + ex.Message); } }, null); }
/// <summary> /// Generates notifications for new Medical Appointments /// </summary> private static void GenerateNotificationsForNewGenericAppointments( [NotNull] CerebelloEntities db, DateTime referenceTime, [NotNull] ICollection <Tuple <Notification, object> > notificationsToBeDispatched) { if (db == null) { throw new ArgumentNullException("db"); } if (notificationsToBeDispatched == null) { throw new ArgumentNullException("notificationsToBeDispatched"); } // check for appointments that have to be notified var timeOffset = referenceTime.AddMinutes(30); var unnotifiedAppointments = db.Appointments.Where( a => !a.Notified && a.Type == (int)TypeAppointment.GenericAppointment && a.Start >= referenceTime && a.Start < timeOffset).ToList(); foreach (var appointment in unnotifiedAppointments) { Debug.Assert(appointment.PatientId != null, "appointment.PatientId != null"); var genericAppointmentData = new GenericAppointmentNotificationData() { Text = appointment.Description, Time = DateTimeHelper.GetFormattedTime( PracticeController.ConvertToLocalDateTime(appointment.Practice, appointment.Start)) }; var genericAppointmentDataString = new JavaScriptSerializer().Serialize(genericAppointmentData); // notify the doctor var newNotification = new Notification() { CreatedOn = referenceTime, IsClosed = false, UserToId = appointment.DoctorId, Type = NotificationConstants.GENERIC_APPOINTMENT_NOTIFICATION_TYPE, PracticeId = appointment.PracticeId, Data = genericAppointmentDataString }; appointment.Doctor.Users.First().Notifications.Add(newNotification); notificationsToBeDispatched.Add(new Tuple <Notification, object>(newNotification, genericAppointmentData)); appointment.Notified = true; } db.SaveChanges(); }
private void CreateDatabaseUsingScript(CerebelloEntities db) { // ToDo: figure out a way to remove this.. we should have a common path or something string scriptText; try { var path = Path.Combine(this.rootCerebelloPath, @"DB\Scripts"); scriptText = File.ReadAllText(Path.Combine(path, "script.sql")); } catch { scriptText = File.ReadAllText("script.sql"); } var scriptText2 = SqlHelper.SetScriptColumnsCollation(scriptText, "Latin1_General_CI_AI"); // We don't want to create users in this script, so we remove them. var script = new SqlScript(); script.Load(scriptText2); script.Items.RemoveAll(x => x.Kind == SqlKinds.User); var scriptText3 = script.ToString(); // Creating tables. Firestarter.ExecuteScript(db, scriptText3); }
private static void SaveLeafletsToDb(CerebelloEntities db, List<MedicineRaw> medicines, Action<int, int> progress = null) { db.ExecuteStoreCommand("delete from SYS_MedicineActiveIngredient"); db.ExecuteStoreCommand("delete from SYS_ActiveIngredient"); db.ExecuteStoreCommand("delete from SYS_Medicine"); db.ExecuteStoreCommand("delete from SYS_Laboratory"); int count, max; { // INGREDIENTS Console.WriteLine("SYS_ActiveIngredient"); List<string> activeIngredientNames = (from m in medicines from ai in m.ActiveIngredient.Split('+') select StringHelper.CapitalizeFirstLetters( Regex.Replace(ai.Trim(), @"\s+", " "), new[] { "a", "o", "ao", "e", "de", "da", "do", "as", "as", "os", "das", "dos", "des" })) .Distinct() .ToList(); count = 0; max = activeIngredientNames.Count; foreach (string activeIngredientName in activeIngredientNames) { if (progress != null) progress(count, max); if (!string.IsNullOrEmpty(activeIngredientName) && activeIngredientName != "-") db.SYS_ActiveIngredient.AddObject(new SYS_ActiveIngredient { Name = activeIngredientName }); if (count % 100 == 0) db.SaveChanges(); count++; } if (progress != null) progress(count, max); // LABORATORIES Console.WriteLine("SYS_Laboratory"); List<string> laboratoryNames = (from m in medicines.ToList() select m.Laboratory).Distinct().ToList(); count = 0; max = laboratoryNames.Count; foreach (string laboratoryName in laboratoryNames) { if (progress != null) progress(count, max); if (!string.IsNullOrEmpty(laboratoryName) && laboratoryName != "-") db.SYS_Laboratory.AddObject(new SYS_Laboratory { Name = laboratoryName }); if (count % 100 == 0) db.SaveChanges(); count++; } if (progress != null) progress(count, max); } db.SaveChanges(); // MEDICINES Console.WriteLine("SYS_Medicine"); var medicinesList = (from m in medicines group m by new { m.Name, m.Concentration }) .Where(mg => mg.Key.Name != "-") .ToList(); count = 0; max = medicinesList.Count; foreach (var medicinesGrouped in medicinesList) { if (progress != null) progress(count, max); string medicineName = medicinesGrouped.Key.Name; var medicine = new SYS_Medicine { Name = medicineName + " (" + medicinesGrouped.Key.Concentration + ")" }; // associating active ingredients with medicine List<string> activeIngredientNames = (from ai in medicinesGrouped.ElementAt(0).ActiveIngredient.Split('+') select StringHelper.CapitalizeFirstLetters( Regex.Replace(ai.Trim(), @"\s+", " "), new[] { "a", "o", "ao", "e", "de", "da", "do", "as", "as", "os", "das", "dos", "des" })) .ToList(); activeIngredientNames = activeIngredientNames .Where(ain => !string.IsNullOrEmpty(ain) && ain != "-") .ToList(); foreach (string ain in activeIngredientNames) { SYS_ActiveIngredient activeIngredient = db.SYS_ActiveIngredient.First(ai => ai.Name == ain); medicine.ActiveIngredients.Add(activeIngredient); } // associating the medicine with the laboratory if (!string.IsNullOrEmpty(medicinesGrouped.ElementAt(0).Laboratory)) { string laboratoryName = medicinesGrouped.ElementAt(0).Laboratory; medicine.Laboratory = db.SYS_Laboratory.First(l => l.Name == laboratoryName); } foreach (var leaflet in medicinesGrouped.Select(mg => new { Description = mg.LeafletType, Url = mg.LeafletUrl })) medicine.Leaflets.Add(new SYS_Leaflet { Description = leaflet.Description, Url = leaflet.Url }); db.SYS_Medicine.AddObject(medicine); db.SaveChanges(); count++; } if (progress != null) progress(count, max); db.SaveChanges(); }
public CerebelloHub() { this.db = this.CreateNewCerebelloEntities(); }
public static void BackupEverything([NotNull] CerebelloEntities db, List <string> errors = null) { if (db == null) { throw new ArgumentNullException("db"); } if (errors == null) { errors = new List <string>(); } using (db) { var dbWrapper = new CerebelloEntitiesAccessFilterWrapper(db); var patientsToBackup = db.Patients.Where(p => p.Doctor.Users.Any(u => u.Person.GoogleUserAccoutInfoes.Any()) && !p.IsBackedUp).GroupBy(p => p.DoctorId); foreach (var patientGroup in patientsToBackup.ToList()) { try { var doctor = db.Doctors.First(d => d.Id == patientGroup.Key); dbWrapper.SetCurrentUserById(doctor.Users.First().Id); var doctorGoogleAccountInfo = doctor.Users.First().Person.GoogleUserAccoutInfoes.FirstOrDefault(); if (doctorGoogleAccountInfo != null) { // in this case the doctor for these patients have a Google Account associated var requestAccessResult = GoogleApiHelper.RequestAccessToken(doctorGoogleAccountInfo.RefreshToken); var authenticator = GoogleApiHelper.GetAuthenticator( doctorGoogleAccountInfo.RefreshToken, requestAccessResult.access_token); var driveService = new DriveService(authenticator); // create Cerebello folder if it does not exist var practiceGoogleDriveInfo = doctor.Practice.GoogleDrivePracticeInfoes.FirstOrDefault(); File cerebelloFolder = null; if (practiceGoogleDriveInfo != null) { try { cerebelloFolder = GoogleApiHelper.GetFile(driveService, practiceGoogleDriveInfo.CerebelloFolderId); if (cerebelloFolder.Labels.Trashed.HasValue && cerebelloFolder.Labels.Trashed.Value) { cerebelloFolder = null; } } catch (Exception ex) { var errorMessage = "Error downloading file from Google Drive. Exception message: " + ex.Message; // the f*****g user deleted the f*****g folder OR something went wrong downloading the file Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage); errors.Add(errorMessage); } } if (cerebelloFolder == null) { cerebelloFolder = GoogleApiHelper.CreateFolder(driveService, "Cerebello", "Pasta do Cerebello"); if (practiceGoogleDriveInfo != null) { practiceGoogleDriveInfo.CerebelloFolderId = cerebelloFolder.Id; } else { practiceGoogleDriveInfo = new GoogleDrivePracticeInfo() { CerebelloFolderId = cerebelloFolder.Id, PracticeId = doctor.PracticeId }; doctor.Practice.GoogleDrivePracticeInfoes.Add(practiceGoogleDriveInfo); } db.SaveChanges(); } foreach (var patient in patientGroup) { try { var patientBackup = GeneratePatientBackup(dbWrapper, patient); var fileName = string.Format("{0} (id:{1})", patient.Person.FullName, patient.Id) + ".zip"; var fileDescription = string.Format( "Arquivo de backup do(a) paciente {0} (id:{1})", patient.Person.FullName, patient.Id); // check if the file exists already var patientGoogleDriveFile = patient.GoogleDrivePatientInfoes.FirstOrDefault(); File googleDrivePatientFile = null; if (patientGoogleDriveFile != null) { try { // get reference to existing file to make sure it exists var existingFile = GoogleApiHelper.GetFile( driveService, patientGoogleDriveFile.PatientBackupFileId); if (!existingFile.Labels.Trashed.HasValue || !existingFile.Labels.Trashed.Value) { googleDrivePatientFile = GoogleApiHelper.UpdateFile( driveService, patientGoogleDriveFile.PatientBackupFileId, fileName, fileDescription, MimeTypesHelper.GetContentType(".zip"), patientBackup); if (googleDrivePatientFile.Labels.Trashed.HasValue && googleDrivePatientFile.Labels.Trashed.Value) { googleDrivePatientFile = null; } } } catch (Exception ex) { var errorMessage = "Error updating file from Google Drive. Exception message: " + ex.Message; // the f*****g user deleted the f*****g folder OR something went wrong downloading the file Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage); errors.Add(errorMessage); } } if (googleDrivePatientFile == null) { googleDrivePatientFile = GoogleApiHelper.CreateFile( driveService, fileName, fileDescription, MimeTypesHelper.GetContentType(".zip"), patientBackup, new List <ParentReference>() { new ParentReference() { Id = cerebelloFolder.Id } }); if (patientGoogleDriveFile != null) { patientGoogleDriveFile.PatientBackupFileId = googleDrivePatientFile.Id; } else { patient.GoogleDrivePatientInfoes.Add( new GoogleDrivePatientInfo() { PatientBackupFileId = googleDrivePatientFile.Id, PracticeId = doctor.PracticeId }); } } patient.IsBackedUp = true; db.SaveChanges(); } catch (Exception ex) { var errorMessage = "Error synchronizing files for a specific doctor. Exception message" + ex.Message; // the f*****g user deleted the f*****g folder OR something went wrong downloading the file Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage); errors.Add(errorMessage); } } } } catch (Exception ex) { var errorMessage = "Error synchronizing files. Exception message" + ex.Message; // the f*****g user deleted the f*****g folder OR something went wrong downloading the file Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage); errors.Add(errorMessage); } } } }
private void InitSysTables(CerebelloEntities db) { Console.WriteLine("Initialize_SYS_MedicalEntity"); Firestarter.Initialize_SYS_MedicalEntity(db); Console.WriteLine("Initialize_SYS_MedicalSpecialty"); Firestarter.Initialize_SYS_MedicalSpecialty(db); Console.WriteLine("Initialize_SYS_Contracts"); Firestarter.Initialize_SYS_Contracts(db); Console.WriteLine("Initialize_SYS_Cid10"); Firestarter.Initialize_SYS_Cid10( db, progress: ConsoleHelper.ConsoleWriteProgressIntInt); Console.WriteLine("Initialize_SYS_MedicalProcedures"); var cbhpmFilePath = Path.Combine(this.rootCerebelloPath, @"DB\cbhpm_2010.txt"); if (!File.Exists(cbhpmFilePath)) { cbhpmFilePath = "cbhpm_2010.txt"; if (!File.Exists(cbhpmFilePath)) throw new Exception("Could not find file cbhpm_2010.txt"); } Firestarter.Initialize_SYS_MedicalProcedures( db, cbhpmFilePath, progress: ConsoleHelper.ConsoleWriteProgressIntInt); Console.WriteLine("SaveLeafletsInMedicinesJsonToDb"); var anvisaHelper = new AnvisaLeafletHelper(); anvisaHelper.SaveLeafletsInMedicinesJsonToDb( db, progress: ConsoleHelper.ConsoleWriteProgressIntInt); // Creating a minimal DB backup called __zero__. if (this.isFuncBackupEnabled) Firestarter.CreateBackup(db, "__zero__"); }
public string StartFullBackup() { var errors = new List<string>(); using (var db = new CerebelloEntities()) { foreach (var patient in db.Patients) patient.IsBackedUp = false; db.SaveChanges(); BackupHelper.BackupEverything(db, errors); } return "Errors : " + string.Join(",", errors); }
protected override void Initialize(System.Web.Routing.RequestContext requestContext) { this.db = this.CreateNewCerebelloEntities(); base.Initialize(requestContext); }
private static void OptionP1(CerebelloEntities db) { // Create practice, contract, doctors and other things Console.WriteLine("Create_CrmMg_Psiquiatria_DrHouse_Andre_Miguel_Thomas"); var doctorsList = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre_Miguel_Thomas(db); // Create practice, contract, doctors and other things Console.WriteLine("CreateSecretary_Milena"); Firestarter.CreateSecretary_Milena(db, doctorsList[0].Users.First().Practice); // Setup doctor schedule and document templates Console.WriteLine("SetupDoctor"); using (var rc = RandomContext.Create()) foreach (var doctor in doctorsList) Firestarter.SetupDoctor(doctor, db, rc.Random.Next()); // Create patients Console.WriteLine("CreateFakePatients"); using (RandomContext.Create()) foreach (var doctor in doctorsList) Firestarter.CreateFakePatients(doctor, db); // Create appointments Console.WriteLine("CreateFakeAppointments"); using (var rc = RandomContext.Create()) foreach (var doctor in doctorsList) Firestarter.CreateFakeAppointments(db, doctor, rc.Random.Next()); }
/// <summary> /// Creates and saves the given number of fake patients /// </summary> public static List<Patient> CreateFakePatients(Doctor doctor, CerebelloEntities db, int count) { var maleFirstNames = new[] { "André", "Anderson", "Alan", "Artur", "Bruno", "Carlos", "Daniel", "Danilo", "Ernani", "Fabiano", "Fábio", "Guilherme", "Hélcio", "Jorge", "Leonardo", "Marcelo", "Miguel", // po cara! eu tb! // blz! haha "Nelson", "Osvaldo", "Patrício", "Roberto", "Ronan", "Thiago" }; var femaleFirstNames = new[] { "Alice", "Aline", "Bianca", "Bruna", "Carla", "Daniela", "Elaine", "Fabíola", "Fabiana", "Giovana", "Íngridi", "Jaqueline", "Larissa", "Marcela", "Natália", "Paula", "Quelen", "Renata", "Silvana", "Tatiana", "Valquíria", "Zilá" }; var middleNames = new[] { "Albuquerque", "Almeida", "Bastos", "Queiróz", "Teixeira", "Silva", "Rodrigues", "Santos", "Pena", "Bicudo", "Gonçalves", "Machado", "Vianna", "Souza", "Moreira", "Vieira", "Correia", "Reis", "Delgado" }; var professions = new[] { "Pedreiro(a)", "Arquiteto(a)", "Programador(a)", "Economista", "Engenheiro(a)", "Padeiro(a)", "Eletricista", "Vendedor(a)", "Consultor(a)", "Biólogo(a)", "Carpinteiro(a)", "Advogado(a)" }; using (var rc = RandomContext.Create()) { var random = rc.Random; var result = new List<Patient>(); for (var i = 0; i < count; i++) { // gender (random upper bound is exclusive) var gender = random.Next(0, 2); // first name var possibleFirstNames = gender == 0 ? maleFirstNames : femaleFirstNames; var firstName = possibleFirstNames[random.Next(possibleFirstNames.Length)]; // middle names var chosenMiddleNames = new string[random.Next(2, 4)]; for (var j = 0; j < chosenMiddleNames.Length; j++) chosenMiddleNames[j] = middleNames[random.Next(middleNames.Length)]; var birthDate = new DateTime( random.Next(1950, 2000), random.Next(1, 13), random.Next(1, 29), 00, 00, 000, DateTimeKind.Utc); var patient = new Patient { Person = new Person { FullName = firstName + " " + string.Join(" ", chosenMiddleNames), Gender = (short)gender, DateOfBirth = birthDate, MaritalStatus = (short?)random.Next(0, 4), BirthPlace = "Brasileiro(a)", CPF = "87324128910", Profession = professions[random.Next(professions.Length)], CreatedOn = Firestarter.UtcNow, PracticeId = doctor.PracticeId, }, Doctor = doctor, PracticeId = doctor.PracticeId, }; // it's important do remove diacritics because StmpClient crashes on non-ascii characters patient.Person.Email = StringHelper.RemoveDiacritics((firstName + string.Join("", chosenMiddleNames)).ToLower() + "@fakemail.com"); Debug.Assert(!patient.Person.Addresses.Any()); patient.Person.Addresses.Add( new Address { CEP = random.Next(36000000, 37000000).ToString(CultureInfo.InvariantCulture), StateProvince = "MG", City = "Juiz de Fora", Neighborhood = "Centro", Street = "Rua " + middleNames[random.Next(middleNames.Length)] + " " + middleNames[random.Next(middleNames.Length)], Complement = "", PracticeId = doctor.PracticeId, }); result.Add(patient); db.Patients.AddObject(patient); } db.SaveChanges(); return result; } }
/// <summary> /// Generates notifications for new Medical Appointments /// </summary> private static void GenerateNotificationsForNewGenericAppointments( [NotNull] CerebelloEntities db, DateTime referenceTime) { GenerateNotificationsForNewGenericAppointments(db, referenceTime, null); }
public virtual void TestInitialize() { scope = new TransactionScope(); this.db = CreateNewCerebelloEntities(); }
public CerebelloHub() { this.db = this.CreateNewCerebelloEntities(); }
public Exec(CerebelloEntities db) { this.db = db; }