public bool UpdateTreatmentPhaseDetail(Model.TreatmentPhaseDetail entity) { var validation = new TreatmentValidation.TreatmentPhaseDetailEntityValidate().Validate(entity); if (!validation.IsValid) { throw new ValidationException(validation.Errors); } using (var db = new Model.PhysicManagementEntities()) { var Entity = db.TreatmentPhaseDetail.Find(entity.Id); if (Entity == null) { throw MegaException.ThrowException("این رکورد در پایگاه داده پیدا نشد."); } var md = new MedicalRecordService(); var MedicalRecordObject = md.GetMedicalRecordById(entity.MedicalRecordId.GetValueOrDefault()); if (MedicalRecordObject == null) { throw MegaException.ThrowException("شناسه پرونده پزشکی وارد شده در پایگاه داده وجود ندارد."); } entity.MedicalRecordId = Convert.ToInt64(MedicalRecordObject.MRICode); Entity.AcceptedDoctorDate = entity.AcceptedDoctorDate; Entity.AcceptedDoctorFullName = entity.AcceptedDoctorFullName; Entity.AcceptedDoctorUserId = entity.AcceptedDoctorUserId; Entity.CancerOARId = entity.CancerOARId; Entity.CancerOARTitle = entity.CancerOARTitle; Entity.CancerOARTolerance = entity.CancerOARTolerance; Entity.CancerTargetId = entity.CancerTargetId; Entity.CancerTargetOptimum = entity.CancerTargetOptimum; Entity.CancerTargetTitle = entity.CancerTargetTitle; Entity.Description = entity.Description; Entity.DoctorDescription = entity.DoctorDescription; Entity.Evaluation = entity.Evaluation; Entity.HadContour = entity.HadContour; Entity.MedicalRecordId = entity.MedicalRecordId; Entity.PatientFirstName = entity.PatientFirstName; Entity.PatientLastName = entity.PatientLastName; Entity.PhysicPlanHasAccepted = entity.PhysicPlanHasAccepted; Entity.PhysicUserFullName = entity.PhysicUserFullName; Entity.PlannedDose = entity.PlannedDose; Entity.PresciptionHasApproved = entity.PresciptionHasApproved; Entity.PrescribedDate = entity.PrescribedDate; Entity.PrescribedDose = entity.PrescribedDose; Entity.PrescribedUser = entity.PrescribedUser; Entity.Reserve3 = entity.Reserve3; Entity.Reserved1 = entity.Reserved1; Entity.Reserved2 = entity.Reserved2; Entity.TreatmentPhaseId = entity.TreatmentPhaseId; return(db.SaveChanges() == 1); } }
public static bool LockUser(int id) { var userEntity = GetUserByUserId(id); if (userEntity == null) { throw MegaException.ThrowException("کاربری با این شناسه در پایگاه داده وجود ندارد"); } UserService.UpdateProfile(userEntity.Id, userEntity.Username, userEntity.FirstName, userEntity.LastName, userEntity.Mobile); return(true); }
public static bool LockUser(int id) { var userEntity = GetUserByUserId(id); if (userEntity == null) { throw MegaException.ThrowException("کاربری با این شناسه در پایگاه داده وجود ندارد"); } ResidentService.UpdateResident(userEntity); return(true); }
public static bool ChangeUserPassword(int userId, string oldPassword, string newPassword) { using (var db = new Model.PhysicManagementEntities()) { var UserData = GetUserByUserId(userId); string encryptedOldPassword = EncryptPassword(UserData.Username, oldPassword); var userData = GetUserData(UserData.Username, oldPassword); if (userData == null) { throw MegaException.ThrowException("رمز وارد شده اشتباه است."); } string encryptedNewPassword = EncryptPassword(userData.Username, newPassword); UserData.Password = encryptedNewPassword; return(db.SaveChanges() == 1); } }
public bool UpdateTreatmentPhase(Model.TreatmentPhase entity) { var validation = new TreatmentValidation.TreatmentPhaseEntityValidate().Validate(entity); if (!validation.IsValid) { throw new ValidationException(validation.Errors); } using (var db = new Model.PhysicManagementEntities()) { var Entity = db.TreatmentPhase.Find(entity.Id); if (Entity == null) { throw MegaException.ThrowException("این رکورد در پایگاه داده پیدا نشد."); } var md = new MedicalRecordService(); var MedicalRecordObject = md.GetMedicalRecordById(entity.MedicalRecordId.GetValueOrDefault()); if (MedicalRecordObject == null) { throw MegaException.ThrowException("شناسه پرونده پزشکی وارد شده در پایگاه داده وجود ندارد."); } //entity.MedicalRecordId = Convert.ToInt64(MedicalRecordObject.MRICode); Entity.PhaseNumber = entity.PhaseNumber; Entity.PhaseText = entity.PhaseText; Entity.PrescribeDate = entity.PrescribeDate; Entity.Target = entity.Target; Entity.Description = entity.Description; Entity.PatientFirstName = MedicalRecordObject.PatientFirstName; Entity.PatientLastName = MedicalRecordObject.PatientLastName; Entity.PhaseText = entity.PhaseText; Entity.TreatmentDeviceId = entity.TreatmentDeviceId; Entity.TreatmentDeviceTitle = entity.TreatmentDeviceTitle; Entity.IsApproved = entity.IsApproved; Entity.Fraction = entity.Fraction; Entity.IsPrescribedByDoctor = entity.IsPrescribedByDoctor; return(db.SaveChanges() == 1); } }
public bool AddTreatmentPhase(Model.TreatmentPhase entity) { var validation = new TreatmentValidation.TreatmentPhaseEntityValidate().Validate(entity); if (!validation.IsValid) { throw new ValidationException(validation.Errors); } using (var db = new Model.PhysicManagementEntities()) { var md = new MedicalRecordService(); var MedicalRecordObject = md.GetMedicalRecordById(entity.MedicalRecordId.GetValueOrDefault()); if (MedicalRecordObject == null) { throw MegaException.ThrowException("شناسه پرونده پزشکی وارد شده در پایگاه داده وجود ندارد."); } db.TreatmentPhase.Add(entity); return(db.SaveChanges() == 1); } }
public static bool UpdateProfile(int id, string userName, string firstName, string lastName, string mobileNo) { var currentUser = GetUserByUserId(id); if (currentUser == null) { throw MegaException.ThrowException("چنین کاربری در سامانه پیدا نشد."); } currentUser.FirstName = firstName; currentUser.LastName = lastName; currentUser.Mobile = mobileNo; var validation = new UserValidation.UserEntityValidate().Validate(currentUser); if (validation.IsValid) { using (var db = new Model.PhysicManagementEntities()) { db.User.Add(currentUser); return(db.SaveChanges() == 1); } } throw new ValidationException(validation.Errors); }
/// <summary> /// Creates a new file in the current folder. This operation is only valid for folders. /// The file is not added to any existing filesystem snapshot, but you can use the returned object to operate on it. /// </summary> /// <param name="name">The name of the file to add.</param> /// <param name="contents">A stream with the contents that the file will have.</param> /// <param name="feedbackChannel">Allows you to receive feedback about the operation while it is running.</param> /// <param name="cancellationToken">Allows you to cancel the operation.</param> public async Task<CloudItem> NewFileAsync(string name, Stream contents, IFeedbackChannel feedbackChannel = null, CancellationToken cancellationToken = default(CancellationToken)) { Argument.ValidateIsNotNullOrWhitespace(name, "name"); Argument.ValidateIsNotNull(contents, "contents"); if (name.IndexOfAny(new[] { '/', '\\' }) != -1) throw new ArgumentException("A file name cannot contain path separator characters.", "name"); if (!IsContainer) throw new InvalidOperationException("This item cannot contain child items."); if (!contents.CanRead) throw new ArgumentException("The contents stream is not readable.", "contents"); if (!contents.CanSeek) throw new ArgumentException("The contents stream is not seekable.", "contents"); PatternHelper.LogMethodCall("NewFileAsync", feedbackChannel, cancellationToken); PatternHelper.EnsureFeedbackChannel(ref feedbackChannel); using (await _client.AcquireLock(feedbackChannel, cancellationToken)) { feedbackChannel.Status = "Preparing for upload"; var beginUploadResult = await _client.ExecuteCommandInternalAsync<BeginUploadResult>(feedbackChannel, cancellationToken, new BeginUploadCommand { Size = contents.Length }); cancellationToken.ThrowIfCancellationRequested(); feedbackChannel.Status = "Uploading file contents"; Base64Data? completionToken = null; // Set when last chunk has been uploaded. var chunkSizes = Algorithms.MeasureChunks(contents.Length); var chunkCount = chunkSizes.Length; var chunkMacs = new byte[chunkCount][]; var dataKey = Algorithms.GetRandomBytes(16); var nonce = Algorithms.GetRandomBytes(8); // Limit number of chunks in flight at the same time. var concurrentUploadSemaphore = new SemaphoreSlim(4); // Only one file read operation can take place at a time. var concurrentReadSemaphore = new SemaphoreSlim(1); // For progress calculations. long completedBytes = 0; CancellationTokenSource chunkUploadsCancellationSource = new CancellationTokenSource(); var uploadTasks = new List<Task>(); for (int i = 0; i < chunkCount; i++) { int chunkIndex = i; long startOffset = chunkSizes.Take(i).Select(size => (long)size).Sum(); uploadTasks.Add(Task.Run(async delegate { var operationName = string.Format("Uploading chunk {0} of {1}", chunkIndex + 1, chunkSizes.Length); using (var chunkFeedback = feedbackChannel.BeginSubOperation(operationName)) { byte[] bytes = new byte[chunkSizes[chunkIndex]]; using (await SemaphoreLock.TakeAsync(concurrentUploadSemaphore)) { chunkUploadsCancellationSource.Token.ThrowIfCancellationRequested(); using (await SemaphoreLock.TakeAsync(concurrentReadSemaphore)) { chunkUploadsCancellationSource.Token.ThrowIfCancellationRequested(); chunkFeedback.Status = "Reading contents"; // Read in the raw bytes for this chunk. contents.Position = startOffset; contents.Read(bytes, 0, bytes.Length); } chunkFeedback.Status = "Encrypting contents"; byte[] chunkMac; Algorithms.EncryptNodeDataChunk(bytes, dataKey, nonce, out chunkMac, startOffset); chunkMacs[chunkIndex] = chunkMac; await RetryHelper.ExecuteWithRetryAsync(async delegate { chunkUploadsCancellationSource.Token.ThrowIfCancellationRequested(); chunkFeedback.Status = string.Format("Uploading {0} bytes", chunkSizes[chunkIndex]); var url = beginUploadResult.UploadUrl + "/" + startOffset; HttpResponseMessage response; using (var client = new HttpClient()) response = await client.PostAsyncCancellationSafe(url, new ByteArrayContent(bytes), chunkUploadsCancellationSource.Token); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); // Result from last chunk is: base64-encoded completion handle to give to NewItemsCommand // Negative ASCII integer in case of error. Standard-ish stuff? // Empty is just OK but not last chunk. if (responseBody.StartsWith("[")) { // Error result! // Assuming it is formatted like this, I never got it to return an error result. // It always just hangs if I do anything funny... var errorResult = JObject.Parse(responseBody); Channel.ThrowOnFailureResult(errorResult); throw new ProtocolViolationException("Got an unexpected result from chunk upload: " + responseBody); } else if (!string.IsNullOrWhiteSpace(responseBody)) { // Completion token! completionToken = responseBody; } if (bytes.Length != chunkSizes[chunkIndex]) throw new MegaException(string.Format("Expected {0} bytes in chunk but got {1}.", chunkSizes[chunkIndex], bytes.Length)); }, ChunkUploadRetryPolicy, chunkFeedback, chunkUploadsCancellationSource.Token); } Interlocked.Add(ref completedBytes, chunkSizes[chunkIndex]); } }, chunkUploadsCancellationSource.Token)); } // Wait for all tasks to finish. Stop immediately on cancel or if any single task fails. while (uploadTasks.Any(d => !d.IsCompleted)) { feedbackChannel.Progress = Interlocked.Read(ref completedBytes) * 1.0 / contents.Length; Exception failureReason = null; if (cancellationToken.IsCancellationRequested) { failureReason = new OperationCanceledException(); } else { var failedTask = uploadTasks.FirstOrDefault(d => d.IsFaulted || d.IsCanceled); if (failedTask != null) { if (failedTask.Exception != null) failureReason = failedTask.Exception.GetBaseException(); else failureReason = new MegaException("The file could not be uploaded."); } } if (failureReason == null) { await Task.Delay(1000); continue; } chunkUploadsCancellationSource.Cancel(); feedbackChannel.Status = "Stopping upload due to subtask failure"; try { // Wait for all of the tasks to complete, just so we do not leave any dangling activities in the background. Task.WaitAll(uploadTasks.ToArray()); } catch { // It will throw something no notify us of the cancellation. Whatever, do not care. } // Rethrow the failure causing exception. ExceptionDispatchInfo.Capture(failureReason).Throw(); } if (!completionToken.HasValue) throw new ProtocolViolationException("Mega did not provide upload completion token."); feedbackChannel.Progress = 1; feedbackChannel.Progress = null; feedbackChannel.Status = "Creating filesystem entry"; var metaMac = Algorithms.CalculateMetaMac(chunkMacs, dataKey); var itemKey = Algorithms.CreateNodeKey(dataKey, nonce, metaMac); var attributesKey = Algorithms.DeriveNodeAttributesKey(itemKey); // Create the file from the uploaded data. var result = await _client.ExecuteCommandInternalAsync<NewItemsResult>(feedbackChannel, cancellationToken, new NewItemsCommand { ClientInstanceID = _client._clientInstanceID, ParentID = ID, Items = new[] { new NewItemsCommand.NewItem { Attributes = new ItemAttributes { { "n", name } }.SerializeAndEncrypt(attributesKey), Type = KnownItemTypes.File, EncryptedItemKey = Algorithms.EncryptKey(itemKey, _client.AesKey), ItemContentsReference = completionToken.Value } } }); _client.InvalidateFilesystemInternal(); return FromTemplate(result.Items.Single(), _client); } }
/// <summary> /// Downloads the contents of the item to the local filesystem. This operation is only valid for files. /// </summary> /// <param name="destinationPath">Path to the destination file that will contain the contents of this item.</param> /// <param name="feedbackChannel">Allows you to receive feedback about the operation while it is running.</param> /// <param name="cancellationToken">Allows you to cancel the operation.</param> public async Task DownloadContentsAsync(string destinationPath, IFeedbackChannel feedbackChannel = null, CancellationToken cancellationToken = default(CancellationToken)) { Argument.ValidateIsNotNullOrWhitespace(destinationPath, "destinationPath"); if (Type != ItemType.File) throw new InvalidOperationException("You can only download files."); PatternHelper.LogMethodCall("DownloadContentsAsync", feedbackChannel, cancellationToken); PatternHelper.EnsureFeedbackChannel(ref feedbackChannel); using (var file = File.Create(destinationPath)) { // If this file does not have any contents, there is nothing to download :) if (!HasContents) return; using (await _client.AcquireLock(feedbackChannel, cancellationToken)) { feedbackChannel.Status = "Requesting download URL"; var result = await _client.ExecuteCommandInternalAsync<GetDownloadLinkResult>(feedbackChannel, cancellationToken, new GetDownloadCommand { ItemID = ID }); feedbackChannel.Status = "Preparing for download"; var itemKey = _client.DecryptItemKey(EncryptedKeys); var dataKey = Algorithms.DeriveNodeDataKey(itemKey); var nonce = itemKey.Skip(16).Take(8).ToArray(); var metaMac = itemKey.Skip(24).Take(8).ToArray(); feedbackChannel.Status = "Pre-allocating file"; file.SetLength(result.Size); feedbackChannel.Status = "Downloading"; var chunkSizes = Algorithms.MeasureChunks(result.Size); var chunkCount = chunkSizes.Length; var chunkMacs = new byte[chunkCount][]; // Limit number of chunks in flight at the same time. var concurrentDownloadSemaphore = new SemaphoreSlim(4); // Only one file write operation can take place at a time. var concurrentWriteSemaphore = new SemaphoreSlim(1); // For progress calculations. long completedBytes = 0; CancellationTokenSource chunkDownloadsCancellationSource = new CancellationTokenSource(); // Get chunks in parallel. List<Task> chunkDownloads = new List<Task>(); for (int i = 0; i < chunkCount; i++) { int chunkIndex = i; long startOffset = chunkSizes.Take(i).Select(size => (long)size).Sum(); long endOffset = startOffset + chunkSizes[i]; // Each chunk is downloaded and processed by this separately. chunkDownloads.Add(Task.Run(async delegate { var operationName = string.Format("Downloading chunk {0} of {1}", chunkIndex + 1, chunkSizes.Length); using (var chunkFeedbackChannel = feedbackChannel.BeginSubOperation(operationName)) { byte[] bytes = null; using (await SemaphoreLock.TakeAsync(concurrentDownloadSemaphore)) { await RetryHelper.ExecuteWithRetryAsync(async delegate { chunkDownloadsCancellationSource.Token.ThrowIfCancellationRequested(); chunkFeedbackChannel.Status = string.Format("Downloading {0} bytes", chunkSizes[chunkIndex]); // Range is inclusive, so do -1 for the end offset. var url = result.DownloadUrl + "/" + startOffset + "-" + (endOffset - 1); HttpResponseMessage response; using (var client = new HttpClient()) response = await client.GetAsyncCancellationSafe(url, chunkDownloadsCancellationSource.Token); response.EnsureSuccessStatusCode(); bytes = await response.Content.ReadAsByteArrayAsync(); if (bytes.Length != chunkSizes[chunkIndex]) throw new MegaException(string.Format("Expected {0} bytes in chunk but got {1}.", chunkSizes[chunkIndex], bytes.Length)); }, ChunkDownloadRetryPolicy, chunkFeedbackChannel, chunkDownloadsCancellationSource.Token); } chunkDownloadsCancellationSource.Token.ThrowIfCancellationRequested(); // OK, got the bytes. Now decrypt them and calculate MAC. chunkFeedbackChannel.Status = "Decrypting"; byte[] chunkMac; Algorithms.DecryptNodeDataChunk(bytes, dataKey, nonce, out chunkMac, startOffset); chunkMacs[chunkIndex] = chunkMac; chunkDownloadsCancellationSource.Token.ThrowIfCancellationRequested(); // Now write to file. chunkFeedbackChannel.Status = "Writing to file"; using (await SemaphoreLock.TakeAsync(concurrentWriteSemaphore)) { file.Position = startOffset; file.Write(bytes, 0, bytes.Length); file.Flush(true); } Interlocked.Add(ref completedBytes, chunkSizes[chunkIndex]); } }, chunkDownloadsCancellationSource.Token)); } // Wait for all tasks to finish. Stop immediately on cancel or if any single task fails. while (chunkDownloads.Any(d => !d.IsCompleted)) { feedbackChannel.Progress = Interlocked.Read(ref completedBytes) * 1.0 / result.Size; Exception failureReason = null; if (cancellationToken.IsCancellationRequested) { failureReason = new OperationCanceledException(); } else { var failedTask = chunkDownloads.FirstOrDefault(d => d.IsFaulted || d.IsCanceled); if (failedTask != null) { if (failedTask.Exception != null) failureReason = failedTask.Exception.GetBaseException(); else failureReason = new MegaException("The file could not be downloaded."); } } if (failureReason == null) { await Task.Delay(1000); continue; } chunkDownloadsCancellationSource.Cancel(); feedbackChannel.Status = "Stopping download due to subtask failure"; try { // Wait for all of the tasks to complete, just so we do not leave any dangling activities in the background. Task.WaitAll(chunkDownloads.ToArray()); } catch { // It will throw something no notify us of the cancellation. Whatever, do not care. } // Rethrow the failure causing exception. ExceptionDispatchInfo.Capture(failureReason).Throw(); } feedbackChannel.Progress = 1; feedbackChannel.Status = "Verifying file"; // Verify meta-MAC. byte[] calculatedMetaMac = Algorithms.CalculateMetaMac(chunkMacs, dataKey); if (!metaMac.SequenceEqual(calculatedMetaMac)) throw new DataIntegrityException("File meta-MAC did not match expected value. File may have been corrupted during download."); } } }