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));
        }
        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();
        }
        /// <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);
            }
        }