/// <summary> /// Checks whether the update activity request is valid. /// <para>This function does not verify whether the activity exists. /// It also does not verify whether a closer proximity server exists to which the activity should be migrated. /// It also does not verify whether the changed activity's start time will be before expiration time.</para> /// </summary> /// <param name="UpdateActivityRequest">Update activity request part of the client's request message.</param> /// <param name="Client">Client that sent the request.</param> /// <param name="RequestMessage">Full request message from client.</param> /// <param name="ErrorResponse">If the function fails, this is filled with error response message that is ready to be sent to the client.</param> /// <returns>true if the update activity request can be applied, false otherwise.</returns> public static bool ValidateUpdateActivityRequest(UpdateActivityRequest UpdateActivityRequest, IncomingClient Client, ProxProtocolMessage RequestMessage, out ProxProtocolMessage ErrorResponse) { log.Trace("()"); bool res = false; ErrorResponse = null; string details = null; if (UpdateActivityRequest == null) { UpdateActivityRequest = new UpdateActivityRequest(); } if (UpdateActivityRequest.Activity == null) { UpdateActivityRequest.Activity = new ActivityInformation(); } SignedActivityInformation signedActivity = new SignedActivityInformation() { Activity = UpdateActivityRequest.Activity, Signature = RequestMessage.Request.ConversationRequest.Signature }; ProxMessageBuilder messageBuilder = Client.MessageBuilder; if (ValidateSignedActivityInformation(signedActivity, Client.PublicKey, messageBuilder, RequestMessage, "", false, out ErrorResponse)) { if (details == null) { int index = 0; foreach (ByteString serverId in UpdateActivityRequest.IgnoreServerIds) { if (serverId.Length != ProtocolHelper.NetworkIdentifierLength) { log.Debug("Ignored server ID #{0} is not a valid network ID as its length is {1} bytes.", index, serverId.Length); details = "ignoreServerIds"; break; } index++; } } if (details == null) { res = true; } else { ErrorResponse = messageBuilder.CreateErrorInvalidValueResponse(RequestMessage, details); } } log.Trace("(-):{0}", res); return(res); }
public async Task <IActionResult> UpdateActivity(int Id, UpdateActivityRequest request) { if (Id != request.Id) { return(BadRequest()); } return(Ok(await _activityService.UpdateActivityRequest(request))); }
public async Task <bool> UpdateActivity(UpdateActivityRequest activityRequest) { try { _bamActivityLogger.Debug($"Updating Stage Activity - {JsonConvert.SerializeObject(activityRequest)}"); activityRequest.Validate(); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.BusinessProcess, activityRequest.BusinessProcess); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.BusinessTransaction, activityRequest.BusinessTransaction); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.CurrentStage, activityRequest.CurrentStage); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.MainActivityId, activityRequest.MainActivityId.ToString()); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.StageActivityId, activityRequest.StageActivityId.ToString()); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.Status, Enum.GetName(typeof(StageStatus), activityRequest.Status)); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.ArchiveMessage, Convert.ToString(activityRequest.IsArchiveEnabled)); _client.DefaultRequestHeaders.AddOrReplace(Constants.Headers.ResourceId, activityRequest.ResourceId); if (activityRequest.MessageHeader == null) { activityRequest.MessageHeader = "{\"Content-Type\":\"application/json\"}"; } if (activityRequest.MessageBody == null) { activityRequest.MessageBody = "{}"; } var header = JsonConvert.DeserializeObject <Dictionary <string, string> >(activityRequest.MessageHeader); header["Content-Type"] = "application/json"; var activityContent = new ActivityContent { MessageBody = activityRequest.MessageBody, MessageHeader = activityRequest.MessageHeader }; var uri = $"{_url}/api/{Constants.Operations.UpdateActivity}"; var data = new StringContent(JsonConvert.SerializeObject(activityContent), Encoding.UTF8, "application/json"); var response = await _client.PostAsync(uri, data); return(response.IsSuccessStatusCode); } catch (Exception ex) { _bamActivityLogger.Error(ex.Message); } return(false); }
public async Task <Response <string> > UpdateActivityRequest(UpdateActivityRequest request) { var activity = await _unitOfWork.ActivityRepository.FirstAsync(x => x.Id == request.Id && x.DelFlag == false); if (activity == null) { return(new Response <string>(null, $"Không tìm thấy activity id \'{request.Id}\'")); } activity.ActivityName = request.ActivityName; activity.MediaFileUrl = request.MediaFileURL; activity.TypeId = request.TypeId; activity.SuitableAge = request.SuitableAge; _unitOfWork.ActivityRepository.UpdateAsync(activity); await _unitOfWork.SaveAsync(); return(new Response <string>(activity.Id.ToString(), "Cập nhật activity thành công")); }
public async Task UpdateAsync(string id, UpdateActivityRequest request) { var entity = await _readRepository.GetByIdAsync(id); var costs = request.Costs .Select(c => { var parameters = c.Parameters .Select(p => new ActivityParameterEntity { VariableName = p.VariableName, Description = p.Description }) .ToArray(); return(new ActivityCostEntity { Kind = c.Kind, JexlExpression = c.JexlExpression, Parameters = parameters }); }) .ToArray(); var updatedEntity = new ActivityEntity { Name = request.Name, DescriptionMarkdown = request.DescriptionMarkdown, ComplicationMarkdown = request.ComplicationMarkdown, Costs = costs }; await(await _container).ReplaceItemAsync( await _entityMutator.UpdateMetadataAsync(updatedEntity, entity, request.SharedWith), id ); }
public JsonResult Update(UpdateActivityRequest body) { _activityRepo.Update(body); return(Json(new { message = "Actividad actualizada exitosamente", success = true })); }
public async Task UpdateAsync(string id, UpdateActivityRequest request) => await _service.UpdateAsync(id, request);
public async Task UpdateAsync(string id, UpdateActivityRequest request) => await _writeRepository.UpdateAsync(id, request);
/// <summary> /// Updates an existing activity in the database. Then a new neighborhood action is created to propagate the changes to the neighborhood /// if this is required. If the update is rejected, the action is deleted from the database and this is propagated to the neighborhood. /// <para>Note that the change in activity is not propagated if the client sets no propagation flag in the request, or if only the activity /// expiration date or its location is changed.</para> /// </summary> /// <param name="UpdateRequest">Update request received from the client.</param> /// <param name="Signature">Signature of the updated activity data from the client.</param> /// <param name="OwnerIdentityId">Network ID of the client who requested the update.</param> /// <param name="CloserServerId">If the result is Status.ErrorRejected, this is filled with network identifier of a neighbor server that is closer to the target location.</param> /// <returns>Status.Ok if the function succeeds, /// Status.ErrorNotFound if the activity to update does not exist, /// Status.ErrorRejected if the update was rejected and the client should migrate the activity to closest proximity server, /// Status.ErrorInvalidValue if the update attempted to change activity's type, /// Status.ErrorInternal otherwise.</returns> public async Task <Status> UpdateAndPropagateAsync(UpdateActivityRequest UpdateRequest, byte[] Signature, byte[] OwnerIdentityId, StrongBox <byte[]> CloserServerId) { log.Trace("(UpdateRequest.Activity.Id:{0},OwnerIdentityId:'{1}')", UpdateRequest.Activity.Id, OwnerIdentityId.ToHex()); Status res = Status.ErrorInternal; bool success = false; bool signalNeighborhoodAction = false; bool migrateActivity = false; ActivityInformation activityInformation = UpdateRequest.Activity; DatabaseLock[] lockObjects = new DatabaseLock[] { UnitOfWork.PrimaryActivityLock, UnitOfWork.FollowerLock, UnitOfWork.NeighborhoodActionLock }; using (IDbContextTransaction transaction = await unitOfWork.BeginTransactionWithLockAsync(lockObjects)) { try { PrimaryActivity existingActivity = (await GetAsync(a => (a.ActivityId == activityInformation.Id) && (a.OwnerIdentityId == OwnerIdentityId))).FirstOrDefault(); if (existingActivity != null) { // First, we check whether the activity should be migrated to closer proximity server. GpsLocation oldLocation = existingActivity.GetLocation(); GpsLocation newLocation = new GpsLocation(activityInformation.Latitude, activityInformation.Longitude); bool locationChanged = !oldLocation.Equals(newLocation); bool error = false; if (locationChanged) { List <byte[]> ignoreServerIds = new List <byte[]>(UpdateRequest.IgnoreServerIds.Select(i => i.ToByteArray())); if (!await unitOfWork.NeighborRepository.IsServerNearestToLocationAsync(newLocation, ignoreServerIds, CloserServerId, ProxMessageBuilder.ActivityMigrationDistanceTolerance)) { if (CloserServerId.Value != null) { migrateActivity = true; log.Debug("Activity's new location is outside the reach of this proximity server, the activity will be deleted from the database."); } else { error = true; } } // else No migration needed } if (!error) { // If it should not be migrated, we update the activity in our database. if (!migrateActivity) { SignedActivityInformation signedActivityInformation = new SignedActivityInformation() { Activity = activityInformation, Signature = ProtocolHelper.ByteArrayToByteString(Signature) }; PrimaryActivity updatedActivity = ActivityBase.FromSignedActivityInformation <PrimaryActivity>(signedActivityInformation); ActivityChange changes = existingActivity.CompareChangeTo(updatedActivity); if ((changes & ActivityChange.Type) == 0) { bool propagateChange = false; if (!UpdateRequest.NoPropagation) { // If only changes in the activity are related to location or expiration time, the activity update is not propagated to the neighborhood. propagateChange = (changes & ~(ActivityChange.LocationLatitude | ActivityChange.LocationLongitude | ActivityChange.PrecisionRadius | ActivityChange.ExpirationTime)) != 0; } existingActivity.CopyFromSignedActivityInformation(signedActivityInformation); Update(existingActivity); if (propagateChange) { // The activity has to be propagated to all our followers we create database actions that will be processed by dedicated thread. signalNeighborhoodAction = await unitOfWork.NeighborhoodActionRepository.AddActivityFollowerActionsAsync(NeighborhoodActionType.ChangeActivity, existingActivity.ActivityId, existingActivity.OwnerIdentityId); } else { log.Trace("Change of activity ID {0}, owner identity ID '{1}' won't be propagated to neighborhood.", existingActivity.ActivityId, existingActivity.OwnerIdentityId.ToHex()); } await unitOfWork.SaveThrowAsync(); transaction.Commit(); success = true; } else { log.Debug("Activity ID {0}, owner identity ID '{1}' attempt to change type.", activityInformation.Id, OwnerIdentityId.ToHex()); res = Status.ErrorInvalidValue; } } // else this is handled below separately, out of locked section } // else Internal error } else { log.Debug("Activity ID {0}, owner identity ID '{1}' does not exist.", activityInformation.Id, OwnerIdentityId.ToHex()); res = Status.ErrorNotFound; } } catch (Exception e) { log.Error("Exception occurred: {0}", e.ToString()); } if (!success) { log.Warn("Rolling back transaction."); unitOfWork.SafeTransactionRollback(transaction); } unitOfWork.ReleaseLock(lockObjects); } if (migrateActivity) { // If activity should be migrated, we delete it from our database and inform our neighbors. StrongBox <bool> notFound = new StrongBox <bool>(false); if (await DeleteAndPropagateAsync(activityInformation.Id, OwnerIdentityId, notFound)) { if (!notFound.Value) { // The activity was deleted from the database and this change will be propagated to the neighborhood. log.Debug("Update rejected, activity ID {0}, owner identity ID '{1}' deleted.", activityInformation.Id, OwnerIdentityId.ToHex()); res = Status.ErrorRejected; } else { // Activity of given ID not found among activities created by the client. res = Status.ErrorNotFound; } } } if (success) { // Send signal to neighborhood action processor to process the new series of actions. if (signalNeighborhoodAction) { Network.NeighborhoodActionProcessor neighborhoodActionProcessor = (Network.NeighborhoodActionProcessor)Base.ComponentDictionary[Network.NeighborhoodActionProcessor.ComponentName]; neighborhoodActionProcessor.Signal(); } res = Status.Ok; } log.Trace("(-):{0}", res); return(res); }