/// <summary>
 /// Deprecated Method for adding a new object to the PatientFileGroups EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToPatientFileGroups(PatientFileGroup patientFileGroup)
 {
     base.AddObject("PatientFileGroups", patientFileGroup);
 }
        private static PatientFilesGroupViewModel GetViewModel(IBlobStorageManager storage, PatientFileGroup dbFileGroup, int dbUserId, Func<DateTime, DateTime> toLocal)
        {
            if (dbFileGroup == null)
                return new PatientFilesGroupViewModel();

            var result = new PatientFilesGroupViewModel
                {
                    Id = dbFileGroup.Id,
                    PatientId = dbFileGroup.PatientId,
                    CreatedOn = dbFileGroup.CreatedOn,
                    Title = dbFileGroup.GroupTitle,
                    Notes = dbFileGroup.GroupNotes,
                    FileGroupDate = toLocal(dbFileGroup.FileGroupDate),
                    ReceiveDate = toLocal(dbFileGroup.ReceiveDate),
                };

            result.Files.AddRange(dbFileGroup.PatientFiles.Select(dbFile => new PatientFileViewModel
                {
                    Id = dbFile.Id,
                    FileTitle = dbFile.Title,
                    ContainerName = dbFile.FileMetadata.ContainerName,
                    SourceFileName = dbFile.FileMetadata.SourceFileName,
                    BlobName = dbFile.FileMetadata.BlobName,
                    ExpirationDate = dbFile.FileMetadata.ExpirationDate,
                    MetadataId = dbFile.FileMetadataId,
                }));

            FillFileLengths(storage, result, dbUserId);

            return result;
        }
 /// <summary>
 /// Create a new PatientFileGroup object.
 /// </summary>
 /// <param name="id">Initial value of the Id property.</param>
 /// <param name="patientId">Initial value of the PatientId property.</param>
 /// <param name="practiceId">Initial value of the PracticeId property.</param>
 /// <param name="groupTitle">Initial value of the GroupTitle property.</param>
 /// <param name="fileGroupDate">Initial value of the FileGroupDate property.</param>
 /// <param name="receiveDate">Initial value of the ReceiveDate property.</param>
 /// <param name="createdOn">Initial value of the CreatedOn property.</param>
 public static PatientFileGroup CreatePatientFileGroup(global::System.Int32 id, global::System.Int32 patientId, global::System.Int32 practiceId, global::System.String groupTitle, global::System.DateTime fileGroupDate, global::System.DateTime receiveDate, global::System.DateTime createdOn)
 {
     PatientFileGroup patientFileGroup = new PatientFileGroup();
     patientFileGroup.Id = id;
     patientFileGroup.PatientId = patientId;
     patientFileGroup.PracticeId = practiceId;
     patientFileGroup.GroupTitle = groupTitle;
     patientFileGroup.FileGroupDate = fileGroupDate;
     patientFileGroup.ReceiveDate = receiveDate;
     patientFileGroup.CreatedOn = createdOn;
     return patientFileGroup;
 }
        public ActionResult Edit(Dictionary<string, PatientFilesGroupViewModel> patientFilesGroups)
        {
            var kv = patientFilesGroups.Single();
            var formModel = kv.Value;

            PatientFileGroup dbFileGroup;

            if (formModel.Id == null)
            {
                Debug.Assert(formModel.PatientId != null, "formModel.PatientId != null");
                dbFileGroup = new PatientFileGroup
                    {
                        PatientId = formModel.PatientId.Value,
                        PracticeId = this.DbUser.PracticeId,
                        CreatedOn = this.datetimeService.UtcNow,
                    };

                this.db.PatientFileGroups.AddObject(dbFileGroup);
            }
            else
            {
                dbFileGroup = this.db.PatientFileGroups
                    .Include("PatientFiles")
                    .Include("PatientFiles.FileMetadata")
                    .FirstOrDefault(pe => pe.Id == formModel.Id);
            }

            Debug.Assert(dbFileGroup != null, "dbFileGroup != null");
            var allExistingFilesInGroup = dbFileGroup.PatientFiles.ToDictionary(pf => pf.Id);

            var idsToKeep = new HashSet<int>(formModel.Files.Where(f => f.Id != null).Select(f => f.Id.Value));

            var storageActions = new List<Action>(formModel.Files.Count);

            var metadataProvider = new DbFileMetadataProvider(this.db, this.datetimeService, this.DbUser.PracticeId);
            var metadataDic = metadataProvider.GetByIds(formModel.Files.Select(f => f.MetadataId).ToArray()).ToDictionary(f => f.Id);

            foreach (var eachFile in formModel.Files)
            {
                // Validating each file location... otherwise this could be a security hole.
                FileMetadata metadata;
                metadataDic.TryGetValue(eachFile.MetadataId, out metadata);

                if (metadata == null)
                    return new StatusCodeResult(HttpStatusCode.NotFound, "Arquivo não encontrado. Outra pessoa deve ter removido esse arquivo neste instante.");

                var validContainer = string.Format("patient-files-{0}", this.DbUser.Id);

                if (metadata.ContainerName != validContainer)
                    throw new Exception("Invalid file location.");

                PatientFile patientFile;

                if (eachFile.Id == null)
                {
                    // creating and adding the new patient file
                    Debug.Assert(formModel.PatientId != null, "formModel.PatientId != null");

                    patientFile = new PatientFile
                    {
                        FileMetadataId = metadata.Id,
                        PatientId = formModel.PatientId.Value,
                        PracticeId = this.DbUser.PracticeId,
                    };

                    dbFileGroup.PatientFiles.Add(patientFile);

                    // changing file metadata:
                    // - it is not temporary anymore
                    // - tag is free for another operation
                    metadata.ExpirationDate = null;
                    metadata.Tag = null;
                }
                else if (!allExistingFilesInGroup.TryGetValue(eachFile.Id.Value, out patientFile))
                {
                    return new StatusCodeResult(HttpStatusCode.NotFound, "Arquivo não encontrado. Outra pessoa deve ter removido esse arquivo neste instante.");
                }

                Debug.Assert(patientFile != null, "patientFile != null");

                patientFile.Title = eachFile.FileTitle;
            }

            // deleting files that were removed
            foreach (var patientFileKv in allExistingFilesInGroup)
            {
                if (!idsToKeep.Contains(patientFileKv.Key))
                {
                    // create delegate to kill the file metadata and the storage blob
                    // this is going to be called latter
                    var metadata = patientFileKv.Value.FileMetadata;
                    Action removeFile = () => TempFileController.DeleteFileByMetadata(metadata, this.db, this.storage);
                    storageActions.Add(removeFile);

                    // delete patient file (note that changes are not being saved yet)
                    this.db.PatientFiles.DeleteObject(patientFileKv.Value);
                }
            }

            if (formModel.Files.Count == 0)
            {
                this.ModelState.AddModelError(string.Format("PatientFilesGroups[{0}].Files", kv.Key), "Deve haver pelo menos um arquivo na lista.");
            }

            if (this.ModelState.IsValid)
            {
                dbFileGroup.GroupTitle = formModel.Title;
                dbFileGroup.GroupNotes = formModel.Notes;
                Debug.Assert(formModel.FileGroupDate != null, "formModel.FileGroupDate != null");
                dbFileGroup.FileGroupDate = this.ConvertToUtcDateTime(formModel.FileGroupDate.Value);
                Debug.Assert(formModel.ReceiveDate != null, "formModel.ReceiveDate != null");
                dbFileGroup.ReceiveDate = this.ConvertToUtcDateTime(formModel.ReceiveDate.Value);

                dbFileGroup.Patient.IsBackedUp = false;
                this.db.SaveChanges();

                // moving files that are stored in a temporary location
                foreach (var moveAction in storageActions)
                    moveAction();

                return this.View("Details", GetViewModel(this.storage, dbFileGroup, this.DbUser.Id, this.GetToLocalDateTimeConverter()));
            }

            FillMissingInfos(formModel, this.db.FileMetadatas);
            FillFileLengths(this.storage, formModel, this.DbUser.Id);

            this.ViewBag.FilesStatusGetter = (FilesStatusGetter)this.GetFilesStatus;

            return this.View("Edit", formModel);
        }