private async Task <DeleteResult> CheckPermission(GeoTask entity,
                                                          Actor currentActor, Project project, bool hardMode)
        {
            ActorRole currentActorProjectRole = null;

            if (project != null && currentActor != null)
            {
                project.ProjectActorRoles.TryGetValue(currentActor.Id,
                                                      out currentActorProjectRole);
            }
            var checkModel = new CheckDeletePermissionModel <GeoTask>
            {
                Entity           = entity,
                Actor            = currentActor,
                ProjectActorRole = currentActorProjectRole,
                HardMode         = hardMode
            };
            var validator       = new GeoTaskDeletePermissionValidator();
            var validatorResult = await validator.ValidateAsync(checkModel)
                                  .ConfigureAwait(false);

            if (!validatorResult.IsValid)
            {
                return(ErrorResult(validatorResult.Errors
                                   .Select(x => x.ErrorMessage)));
            }
            return(new DeleteResult {
                Success = true
            });
        }
Exemple #2
0
        public ActionResult Delete(int?id, bool?ismovie, bool?ispeople)
        {
            if ((id == null) || (ismovie == null && ispeople == null) || (ismovie == false && ispeople == false) || (ismovie == true && ispeople == true))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ActorRole actorRole = db.ActorRoles.Include(ar => ar.Movie).Include(ar => ar.People).FirstOrDefault(ar => ar.ActorRoleID == id);

            if (actorRole == null)
            {
                return(HttpNotFound());
            }

            if (ismovie != null)
            {
                ViewBag.MovieID  = actorRole.MovieID;
                ViewBag.PeopleID = new SelectList(db.Peoples.Where(p => p.Proffesion.Actor == true), "PeopleID", "FullName");
                ViewBag.Name     = actorRole.Movie.TitleYear;
            }
            else
            if (ispeople != null)
            {
                ViewBag.MovieID  = new SelectList(db.Movies, "MovieID", "TitleYear");
                ViewBag.PeopleID = actorRole.PeopleID;
                ViewBag.Name     = actorRole.People.FullName;
            }

            return(View(actorRole));
        }
        public async Task <int> UpdateAR(int id, ActorInScenarioAddVM arEditModel)
        {
            ActorRole ar = await _context.ActorRoles.FindAsync(id);

            if (ar == null)
            {
                return(-1);
            }
            ar.ActorInScenario      = arEditModel.ActorInScenario;
            ar.RoleScenarioId       = arEditModel.RoleScenarioId;
            ar.ActorRoleDescription = arEditModel.ActorRoleDescription;
            ar.DateUpdate           = arEditModel.DateUpdate;
            ar.Admin = arEditModel.Admin;

            _context.Entry(ar).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();

                return(ar.ActorRoleId);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ArExists(id))
                {
                    return(-1);
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #4
0
        private void ActorBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ActorBox.Items.Count == 0 || ActorBox.SelectedIndex == -1)
            {
                return;
            }
            else
            {
                searchByRoleActor.Enabled = true;
                ActorRole x = (ActorRole)ActorBox.SelectedItem;

                SearchByActor.Text     = x.Name;
                searchByRoleActor.Text = "Movies By " + x.Name;

                String        conString  = @"Data Source=SHERIF\SQLEXPRESS;Initial Catalog=PopCornia;Persist Security Info=True;User ID=sa;Password=123456";
                SqlConnection connection = new SqlConnection(conString);
                connection.Open();
                SqlCommand query = new SqlCommand();
                query.CommandText = "SELECT * FROM FavActors WHERE User_ID = '" + ID + "' AND Actor_ID = '" + x.Key + "';";
                query.Connection  = connection;
                query.CommandType = CommandType.Text;
                SqlDataReader reader = query.ExecuteReader();
                FAV.Text = "★";
                while (reader.Read())
                {
                    FAV.Text = "☆";
                }
            }
        }
Exemple #5
0
        private void FAV_Click(object sender, EventArgs e)
        {
            if (ActorBox.SelectedIndex == -1)
            {
                return;
            }
            ActorRole x = (ActorRole)ActorBox.SelectedItem;

            if (FAV.Text == "★")
            {
                String        conString  = @"Data Source=SHERIF\SQLEXPRESS;Initial Catalog=PopCornia;Persist Security Info=True;User ID=sa;Password=123456";
                SqlConnection connection = new SqlConnection(conString);
                connection.Open();
                SqlCommand query = new SqlCommand();
                query.CommandText = "INSERT INTO FavActors VALUES (" + x.Key + ", " + ID + ");";
                query.Connection  = connection;
                query.CommandType = CommandType.Text;
                SqlDataReader reader = query.ExecuteReader();
                FAV.Text = "☆";
            }
            else
            {
                Movie         movie      = (Movie)QueryBox.SelectedItem;
                String        conString  = @"Data Source=SHERIF\SQLEXPRESS;Initial Catalog=PopCornia;Persist Security Info=True;User ID=sa;Password=123456";
                SqlConnection connection = new SqlConnection(conString);
                connection.Open();
                SqlCommand query = new SqlCommand();
                query.CommandText = "DELETE FROM FavActors WHERE User_ID = '" + ID + "' AND Actor_ID = '" + x.Key + "';";
                query.Connection  = connection;
                query.CommandType = CommandType.Text;
                SqlDataReader reader = query.ExecuteReader();
                FAV.Text = "★";
            }
            updateFavActor();
        }
Exemple #6
0
 public RentalContractProcessDefinition()
 {
     actorRenter           = new ActorRole("Renter");
     actorDriver           = new ActorRole("Driver");
     actorCarIssuer        = new ActorRole("Car issuer");
     actorRentalContracter = new ActorRole("Rental contracter");
 }
        private async Task <CreateResult> CheckPermission(GeoTask task,
                                                          Actor actor, Project project)
        {
            ActorRole currentActorProjectRole = null;

            if (project != null && actor != null)
            {
                project.ProjectActorRoles?
                .TryGetValue(actor.Id, out currentActorProjectRole);
            }
            var checkModel = new CheckCreatePermissionModel <GeoTask>
            {
                Entity           = task,
                Actor            = actor,
                ProjectActorRole = currentActorProjectRole
            };
            var validator       = new GeoTaskCreatePermissionValidator();
            var validatorResult = await validator
                                  .ValidateAsync(checkModel)
                                  .ConfigureAwait(false);

            if (!validatorResult.IsValid)
            {
                return(ErrorResult(validatorResult.Errors
                                   .Select(x => x.ErrorMessage)));
            }
            return(new CreateResult {
                Success = true, Id = task.Id
            });
        }
        public static ActorRole Read(String login, Boolean WithActive = true, Boolean WithDeleted = false)
        {
            Actor     act    = ActorTools.Read(login, WithActive, WithDeleted);
            Role      rol    = RoleTools.Read(act.RoleId);
            ActorRole result = new ActorRole(act, rol);

            return(result);
        }
        public ActorRole Create(ActorRole newRole, SUGARContext context = null)
        {
            newRole = _actorRoleDbController.Create(newRole, context);

            _logger.LogInformation($"{newRole?.Id}");

            return(newRole);
        }
Exemple #10
0
 public Actor(string name, Point2i position, GameTile presentation, Direction direction, ActorBrain brain, ActorRole role, List <string> dialogue)
 {
     Name         = name;
     Position     = position;
     Presentation = presentation;
     Direction    = direction;
     Brain        = brain;
     Role         = role;
     Inventory    = new List <Item>();
     Dialogue     = dialogue;
     Conditions   = new List <Condition>();
 }
Exemple #11
0
        public ActionResult Create([Bind(Include = "ActorRoleID,PeopleID,MovieID,RoleName,Dubbing")] ActorRole actorRole, bool?ismovie, bool?ispeople)
        {
            if ((ismovie == null && ispeople == null) || (ismovie == false && ispeople == false) || (ismovie == true && ispeople == true))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (ismovie != null)
            {
                actorRole.Movie = db.Movies.Find(actorRole.MovieID);
                if (actorRole.Movie == null)
                {
                    return(HttpNotFound());
                }

                ViewBag.MovieID  = actorRole.MovieID;
                ViewBag.PeopleID = new SelectList(db.Peoples.Where(p => p.Proffesion.Actor == true), "PeopleID", "FullName");
                ViewBag.Name     = actorRole.Movie.TitleYear;
            }
            else
            if (ispeople != null)
            {
                actorRole.People = db.Peoples.Find(actorRole.PeopleID);
                if (actorRole.People == null)
                {
                    return(HttpNotFound());
                }
                ViewBag.MovieID  = new SelectList(db.Movies, "MovieID", "TitleYear");
                ViewBag.PeopleID = actorRole.PeopleID;
                ViewBag.Name     = actorRole.People.FullName;
            }

            if (ModelState.IsValid)
            {
                db.ActorRoles.Add(actorRole);
                db.SaveChanges();
                if (ismovie == true)
                {
                    TempData["Success"] = "Członek obsady został dodany.";
                    return(RedirectToAction("Details", "Movies", new { id = actorRole.MovieID }));
                }
                else if (ispeople == true)
                {
                    TempData["Success"] = "Rola została dodana";
                    return(RedirectToAction("Details", "People", new { id = actorRole.PeopleID }));
                }
            }
            ViewData["Error"] = "Nie można zapisać, popraw błędy!";
            return(View());
        }
Exemple #12
0
        public ActorRole ToActorRole()
        {
            ActorRole a = new ActorRole();

            a.actor = new Actor {
                name = this.name
            };

            a.tvDbId   = this.id;
            a.role     = this.role;
            a.imageUrl = this.image;

            return(a);
        }
Exemple #13
0
        public static ActorRoleResponse ToContract(this ActorRole actorRoleModel)
        {
            if (actorRoleModel == null)
            {
                return(null);
            }

            return(new ActorRoleResponse {
                Id = actorRoleModel.Id,
                ActorId = actorRoleModel.ActorId,
                RoleId = actorRoleModel.RoleId,
                EntityId = actorRoleModel.EntityId
            });
        }
        public DbGetGeoTaskListRequestSecurityBuilder
            (DbGetGeoTaskListRequest filter, Actor currentActor,
            ActorRole projectActorRole = null)
        {
            if (filter is null)
            {
                throw new System.ArgumentNullException(nameof(filter));
            }

            if (currentActor is null)
            {
                throw new System.ArgumentNullException(nameof(currentActor));
            }

            Filter           = filter;
            Actor            = currentActor;
            ProjectActorRole = projectActorRole;
        }
Exemple #15
0
        private async Task <ValidationResult> CheckPermissionAsync
            (_TEntity oldEntity, _TEntity newEntity, Actor currentActor,
            ActorRole currentProjectRole)
        {
            var checkModel = new CheckUpdatePermissionModel <_TEntity>
            {
                Actor = currentActor,
                EntityBeforeUpdate = oldEntity,
                EntityAfterUpdate  = newEntity,
                NewProjectRole     = currentProjectRole,
                OldProjectRole     = currentProjectRole
            };
            var validator       = new UpdatePermissionValidator <_TEntity>();
            var validatorResult = await validator.ValidateAsync(checkModel)
                                  .ConfigureAwait(false);

            return(validatorResult);
        }
        private async Task <ValidationResult> CheckPermissionAsync
            (GeoTask oldTask, GeoTask newTask, Actor currentActor,
            ActorRole oldProjectRole, ActorRole newProjectRole)
        {
            var checkModel = new CheckUpdatePermissionModel <GeoTask>
            {
                Actor              = currentActor,
                OldProjectRole     = oldProjectRole,
                NewProjectRole     = newProjectRole,
                EntityBeforeUpdate = oldTask,
                EntityAfterUpdate  = newTask
            };
            var validator       = new GeoTaskUpdatePermissionValidator();
            var validatorResult = await validator
                                  .ValidateAsync(checkModel)
                                  .ConfigureAwait(false);

            return(validatorResult);
        }
Exemple #17
0
        public ActorRole Create(ActorRole actorRole, SUGARContext context = null)
        {
            var didCreate = false;

            if (context == null)
            {
                context   = ContextFactory.Create();
                didCreate = true;
            }

            context.ActorRoles.Add(actorRole);

            if (didCreate)
            {
                context.SaveChanges();
                context.Dispose();
            }

            return(actorRole);
        }
Exemple #18
0
        public ActionResult DeleteConfirmed(int?id, bool?ismovie, bool?ispeople)
        {
            if ((id == null) || (ismovie == null && ispeople == null) || (ismovie == false && ispeople == false) || (ismovie == true && ispeople == true))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ActorRole actorRole = db.ActorRoles.Find(id);

            if (actorRole == null)
            {
                return(HttpNotFound());
            }

            int redirectid = 0;

            if (ismovie == true)
            {
                redirectid = actorRole.MovieID;
            }
            else if (ispeople == true)
            {
                redirectid = actorRole.PeopleID;
            }

            db.ActorRoles.Remove(actorRole);
            db.SaveChanges();

            if (ismovie == true)
            {
                TempData["Success"] = "Członek obsady został usunięty.";
                return(RedirectToAction("Details", "Movies", new { id = redirectid }));
            }
            else if (ispeople == true)
            {
                TempData["Success"] = "Rola została usunięta.";
                return(RedirectToAction("Details", "People", new { id = redirectid }));
            }
            TempData["Success"] = "Usunięto.";
            return(RedirectToAction("Index", "Home"));
        }
Exemple #19
0
        private async Task <CreateResult> CheckPermission
            (_TEntity entity, Actor currentActor, ActorRole currentProjectRole)
        {
            var checkModel = new CheckCreatePermissionModel <_TEntity>
            {
                Entity           = entity,
                Actor            = currentActor,
                ProjectActorRole = currentProjectRole
            };
            var validator       = new CreatePermissionValidator <_TEntity>();
            var validatorResult = await validator.ValidateAsync(checkModel)
                                  .ConfigureAwait(false);

            if (!validatorResult.IsValid)
            {
                return(ErrorResult(validatorResult.Errors
                                   .Select(x => x.ErrorMessage)));
            }
            return(new CreateResult {
                Success = true
            });
        }
        public async Task AddActorInScenario(ActorInScenarioAddVM addModel)
        {
            ActorRole actorInRole = new ActorRole();

            actorInRole.ActorInScenario      = addModel.ActorInScenario;
            actorInRole.RoleScenarioId       = addModel.RoleScenarioId;
            actorInRole.ScenarioId           = addModel.ScenarioId;
            actorInRole.ActorRoleDescription = addModel.ActorRoleDescription;
            actorInRole.DateUpdate           = addModel.DateUpdate;
            actorInRole.Admin    = addModel.Admin;
            actorInRole.IsDelete = IsDelete.ACTIVE;


            _context.ActorRoles.Add(actorInRole);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                Debug.WriteLine(e.InnerException.Message);
                throw;
            }
        }
Exemple #21
0
        public async Task <UpdateResult> Handle(_TUpdateCommand command,
                                                CancellationToken cancellationToken)
        {
            try
            {
                Logger.LogInformation(AppLogEvent.HandleRequest,
                                      "Handle Geo Update Command {Command}",
                                      command.ToDictionary());

                if (command is null || string.IsNullOrWhiteSpace(command.Id))
                {
                    Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                      "Geo Update Command is empty");
                    return(ErrorResult("Geo Update Command is empty"));
                }

                // Validate Update Command
                var validator        = new GeoUpdateCommandValidator();
                var validationResult = await validator
                                       .ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    var validationErrors = validationResult.Errors
                                           .Select(x => x.ErrorMessage)
                                           .ToList();
                    Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                      "Geo Update Command validation error. " +
                                      "Command={Command}. Error={Error}.",
                                      command.ToDictionary(), validationErrors);
                    return(ErrorResult(validationErrors));
                }

                // Get entity before update
                var oldEntityResponse = await Mediator
                                        .Send(new DbGetEntityByIdRequest <_TEntity>(command.Id))
                                        .ConfigureAwait(false);

                if (!oldEntityResponse.Success)
                {
                    Logger.LogWarning(AppLogEvent.HandleErrorResponse,
                                      "Get entity for update error. Id={Id}. Error={Error}",
                                      command.Id, oldEntityResponse.Errors);
                    return(ErrorResult(oldEntityResponse.Errors));
                }
                var oldEntity = oldEntityResponse.Entity;

                // Get current actor
                var currentActorResponse = await Mediator
                                           .Send(new DbGetActorByNameRequest
                                                 (command.CurrentPrincipal?.Identity?.Name))
                                           .ConfigureAwait(false);

                var currentActor = currentActorResponse.Success
                    ? currentActorResponse.Entity
                    : null;

                // Build updated entity
                _TEntity newEntity = await BuildUpdatedEntity
                                         (command, oldEntity)
                                     .ConfigureAwait(false);

                // Validate updated entity before update
                var validatorBeforeSave        = new BeforeSaveValidator <_TEntity>();
                var validationBeforeSaveResult = await validatorBeforeSave
                                                 .ValidateAsync(newEntity)
                                                 .ConfigureAwait(false);

                if (!validationBeforeSaveResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Update Geo validation error. Entity={Entity}. " +
                                      "Error={Error}.", newEntity.ToDictionary(),
                                      validationBeforeSaveResult.Errors);
                    return(ErrorResult(validationBeforeSaveResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get project role of current actor
                var projectResponse = await Mediator
                                      .Send(new DbGetEntityByIdRequest <Project>
                                            (oldEntity.ProjectId))
                                      .ConfigureAwait(false);

                ActorRole currentProjectRole = null;
                if (projectResponse.Success)
                {
                    projectResponse.Entity.ProjectActorRoles
                    .TryGetValue(currentActor.Id, out currentProjectRole);
                }

                // Check permission to update
                var permissionValidateResult = await CheckPermissionAsync
                                                   (oldEntity, newEntity, currentActor, currentProjectRole)
                                               .ConfigureAwait(false);

                if (!permissionValidateResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Current actor has no rights to update entity. " +
                                      "Actor={Actor}. " +
                                      "CurrentActorProjectRole={CurrentActorProjectRole}. " +
                                      "Entity before update={OldEntity}. " +
                                      "Entity after update={NewEntity}. Error={Error}.",
                                      currentActor.ToDictionary(), currentProjectRole,
                                      oldEntity.ToDictionary(), newEntity.ToDictionary(),
                                      permissionValidateResult.Errors
                                      .Select(x => x.ErrorMessage));
                    return(ErrorResult(permissionValidateResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Save updated entity
                var updateResult = await Mediator
                                   .Send(new DbUpdateCommand <_TEntity>(newEntity))
                                   .ConfigureAwait(false);

                return(updateResult);
            }

            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Geo update exception");
                return(ErrorResult("Geo update exception"));
            }
        }
        public async Task <UpdateResult> Handle(GeoTaskUpdateCommand command,
                                                CancellationToken cancellationToken)
        {
            try
            {
                Logger.LogInformation(AppLogEvent.HandleRequest,
                                      "Handle update task {Command}", command.ToDictionary());

                if (command is null || string.IsNullOrWhiteSpace(command.Id))
                {
                    Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                      "Handle update task command with empty request");
                    return(ErrorResult("Command empty argument"));
                }

                var validator        = new GeoTaskUpdateCommandValidator();
                var validationResult = await validator.ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    var validationErrors = validationResult.Errors
                                           .Select(x => x.ErrorMessage).ToList();
                    Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                      "Task update command validation error. " +
                                      "Command={Command}. Error={Error}",
                                      command.ToDictionary(), validationErrors);
                    return(ErrorResult(validationErrors));
                }

                var oldGeoTaskResponse = await Mediator
                                         .Send(new DbGetEntityByIdRequest <GeoTask>(command.Id))
                                         .ConfigureAwait(false);

                if (!oldGeoTaskResponse.Success)
                {
                    Logger.LogWarning(AppLogEvent.HandleErrorResponse,
                                      "Get task for update error. Id={Id}. Error={Error}.",
                                      command.Id, oldGeoTaskResponse.Errors);
                    return(ErrorResult(oldGeoTaskResponse.Errors));
                }
                var oldGeoTask = oldGeoTaskResponse.Entity;

                var currentActorResponse = await Mediator
                                           .Send(new DbGetActorByNameRequest
                                                 (command.CurrentPrincipal?.Identity?.Name))
                                           .ConfigureAwait(false);

                var currentActor = currentActorResponse.Entity;

                OldProject = await GetProjectAsync(oldGeoTask.ProjectId)
                             .ConfigureAwait(false);

                // Check Project Id
                NewProject = null;
                if (command.ProjectId != OldProject?.Id)
                {
                    NewProject = await GetProjectAsync(command.ProjectId)
                                 .ConfigureAwait(false);
                }
                else
                {
                    NewProject = OldProject;
                }

                GeoTask newGeoTask = await BuildUpdatedGeoTask(command,
                                                               oldGeoTask, currentActor).ConfigureAwait(false);

                var validatorBeforeSave        = new GeoTaskBeforeSaveValidator();
                var validationBeforeSaveResult = await validatorBeforeSave
                                                 .ValidateAsync(newGeoTask)
                                                 .ConfigureAwait(false);

                if (!validationBeforeSaveResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Update GeoTask validation error. " +
                                      "Entity={Entity}. Error={Error}.",
                                      newGeoTask.ToDictionary(),
                                      validationBeforeSaveResult.Errors);
                    return(ErrorResult(validationBeforeSaveResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                ActorRole oldProjectRole = null;
                OldProject?.ProjectActorRoles?
                .TryGetValue(currentActor.Id, out oldProjectRole);
                ActorRole newProjectRole = null;
                if (oldGeoTask.ProjectId != newGeoTask.ProjectId)
                {
                    NewProject?.ProjectActorRoles?
                    .TryGetValue(currentActor.Id, out newProjectRole);
                }
                else
                {
                    newProjectRole = oldProjectRole;
                }

                var permissionValidateResult = await CheckPermissionAsync
                                                   (oldGeoTask, newGeoTask, currentActor,
                                                   oldProjectRole, newProjectRole)
                                               .ConfigureAwait(false);

                if (!permissionValidateResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Current actor has no rights to update GeoTask. " +
                                      "Actor={Actor}. Entity before update={OldEntity}." +
                                      " Entity after update={NewEntity}. Error={Error}.",
                                      currentActor.ToDictionary(), oldGeoTask.ToDictionary(),
                                      newGeoTask.ToDictionary(),
                                      permissionValidateResult.Errors
                                      .Select(x => x.ErrorMessage));
                    return(ErrorResult(permissionValidateResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                var updateResult = await Mediator
                                   .Send(new DbUpdateCommand <GeoTask>(newGeoTask))
                                   .ConfigureAwait(false);

                return(updateResult);
            }

            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Geo task update exception");
                return(ErrorResult("Geo task update exception"));
            }
        }
 public InitCompletedMessage(ActorRole role)
 {
     Role = role;
 }
Exemple #24
0
        public async Task <ListResponse <GeoTask> > Handle
            (GeoTaskListQuery request, CancellationToken cancellationToken)
        {
            Logger.LogInformation(AppLogEvent.HandleRequest,
                                  "Handle get task collection {request}",
                                  request.ToDictionary());

            if (request is null)
            {
                Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                  "Handle get task collection request with empty request");
                return(ErrorResponse("Request empty argument"));
            }

            try
            {
                // Validate request
                var validator        = new GeoTaskListQueryValidator();
                var validationResult = await validator.ValidateAsync(request)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    Logger.LogError("Query validation error. " +
                                    "Request={Request}. Error={Error}.",
                                    request.ToDictionary(),
                                    validationResult.Errors.Select(x => x.ErrorMessage));
                    return(ErrorResponse
                               (validationResult.Errors.Select(x => x.ErrorMessage)));
                }

                // Build filter
                var defaultLimit = Configuration.GetValue
                                       (Defaults.ConfigurationApiDefaultLimitParameterName,
                                       Defaults.ConfigurationApiDefaultLimitDefaultValue);
                var maxLimit = Configuration.GetValue
                                   (Defaults.ConfigurationApiMaxLimitParameterName,
                                   Defaults.ConfigurationApiMaxLimitDefaultValue);
                var filter = new DbGetGeoTaskListRequest
                {
                    Offset = request.Offset,
                    Limit  = request.Limit == 0
                        ? defaultLimit
                        : Math.Min(request.Limit, maxLimit),
                    Archived          = request.Archived,
                    Contains          = request.СontainsKeyWords,
                    MaxTimeToDeadLine = request.MaxTimeToDeadLine,
                    TaskStatusMask    = request.TaskStatusMask,
                };
                if (!String.IsNullOrWhiteSpace(request.ActorId))
                {
                    filter.Actors[request.ActorId] = request.ActorRoleMask;
                }
                if (!string.IsNullOrWhiteSpace(request.ProjectId))
                {
                    filter.ProjectIds.Add(request.ProjectId);
                }
                filter.GeoIds.AddRange(request.GeoIds);

                // Get Actor for current user by user name
                var currentActorResponse = await Mediator
                                           .Send(new DbGetActorByNameRequest
                                                 (request.CurrentPrincipal?.Identity?.Name))
                                           .ConfigureAwait(false);

                Actor currentActor = null;
                if (currentActorResponse.Success)
                {
                    currentActor = currentActorResponse.Entity;
                }
                else
                {
                    Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                      "Not found current actor");
                    return(ErrorResponse("Not found current actor"));
                }

                ActorRole projectActorRole = null;
                if (!string.IsNullOrWhiteSpace(request.ProjectId))
                {
                    projectActorRole = await GetProjectRoleAsync
                                           (request.ProjectId, currentActor?.Id)
                                       .ConfigureAwait(false);
                }

                // Apply security filter
                var securizator = new DbGetGeoTaskListRequestSecurityBuilder
                                      (filter, currentActor, projectActorRole);
                var securedFilter = securizator.Build();

                return(await Mediator.Send(securedFilter)
                       .ConfigureAwait(false));
            }
            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Call repository exception");
                return(ErrorResponse("Not found"));
            }
        }
Exemple #25
0
        public MovieManager()
        {
            var gl = new Person()
            {
                Name = "George Lucas"
            };
            var ik = new Person()
            {
                Name = "Irvin Kershner"
            };
            var rm = new Person()
            {
                Name = "Richard Marquand"
            };
            var jj = new Person()
            {
                Name = "J. J. Abrams"
            };
            var rj = new Person()
            {
                Name = "Rian Johnson"
            };

            var mh = new Person()
            {
                Name = "Mark Hamill"
            };
            var ls = new ActorRole()
            {
                Person = mh, RoleName = "Luke Skywalker"
            };

            var hf = new Person()
            {
                Name = "Harrison Ford"
            };
            var hs = new ActorRole()
            {
                Person = hf, RoleName = "Han Solo"
            };

            var cf = new Person()
            {
                Name = "Carrie Fisher"
            };
            var pl = new ActorRole()
            {
                Person = cf, RoleName = "Princess Leia"
            };

            var mg = new Person()
            {
                Name = "Ewan McGregor"
            };
            var obi1 = new ActorRole {
                Person = mg, RoleName = "Obi-Wan Kenobi"
            };

            var ag = new Person()
            {
                Name = "Alec Guinness"
            };
            var obi2 = new ActorRole {
                Person = ag, RoleName = "Obi-Wan Kenobi"
            };

            var sw1 = new Movie()
            {
                Title = "Star Wars: Episode I – The Phantom Menace", PublishedDate = new DateTime(1999, 5, 19), Revenue = 1027044677m, Director = gl
            };
            var sw2 = new Movie()
            {
                Title = "Star Wars: Episode II – Attack of the Clones", PublishedDate = new DateTime(2002, 5, 16), Revenue = 656695615m, Director = ik
            };
            var sw3 = new Movie()
            {
                Title = "Star Wars: Episode III – Revenge of the Sith", PublishedDate = new DateTime(2005, 5, 19), Revenue = 848998877m, Director = rm
            };
            var sw4 = new Movie()
            {
                Title = "Star Wars: Episode IV – A New Hope", PublishedDate = new DateTime(1977, 5, 25), Revenue = 786598007m, Director = gl
            };
            var sw5 = new Movie()
            {
                Title = "Star Wars: Episode V – The Empire Strikes Back", PublishedDate = new DateTime(1980, 5, 21), Revenue = 534161334m, Director = gl
            };
            var sw6 = new Movie()
            {
                Title = "Star Wars: Episode VI – Return of the Jedi", PublishedDate = new DateTime(1983, 5, 25), Revenue = 572705079m, Director = gl
            };
            var sw7 = new Movie()
            {
                Title = "Star Wars: Episode VII – The Force Awakens", PublishedDate = new DateTime(2015, 12, 18), Revenue = 2053311220m, Director = jj
            };
            var sw8 = new Movie()
            {
                Title = "Star Wars: Episode VIII – The Last Jedi", PublishedDate = new DateTime(2017, 12, 15), Revenue = 1316764784m, Director = rj
            };
            var sw9 = new Movie()
            {
                Title = "Star Wars: Episode IX – ???", PublishedDate = new DateTime(2019, 12, 20), Revenue = 0m, Director = jj
            };


            sw1.ActorRoles.Add(obi1);
            sw2.ActorRoles.Add(obi1);
            sw3.ActorRoles.Add(obi1);
            sw4.ActorRoles.Add(ls);
            sw4.ActorRoles.Add(pl);
            sw4.ActorRoles.Add(hs);
            sw4.ActorRoles.Add(obi2);
            sw5.ActorRoles.Add(ls);
            sw5.ActorRoles.Add(pl);
            sw5.ActorRoles.Add(hs);
            sw5.ActorRoles.Add(obi2);
            sw6.ActorRoles.Add(ls);
            sw6.ActorRoles.Add(pl);
            sw6.ActorRoles.Add(hs);
            sw6.ActorRoles.Add(obi2);


            Movies = new List <Movie>(new[] { sw1, sw2, sw3, sw4, sw5, sw6, sw7, sw8, sw9 });
            Movies.Where(x => x.Director == gl).ToList().ForEach(x => gl.Movies.Add(x));
            Movies.Where(x => x.Director == jj).ToList().ForEach(x => jj.Movies.Add(x));
            ik.Movies.Add(sw2);
            rm.Movies.Add(sw3);
            rj.Movies.Add(sw8);
        }
Exemple #26
0
        public async Task <CreateResult> Handle(_TCreateCommand command,
                                                CancellationToken cancellationToken)
        {
            Logger.LogInformation(AppLogEvent.HandleRequest,
                                  "Handle Geo Create Command. Command={Command}",
                                  command.ToDictionary());

            if (command is null)
            {
                Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                  "Handle Geo Create Command got empty command");
                return(ErrorResult("Empty Geo Create Command"));
            }

            try
            {
                var validator        = new CreateCommandValidator <_TCreateCommand>();
                var validationResult = await validator.ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Validation command error. Command={Command}. " +
                                      "Error={Error}.",
                                      command.ToDictionary(), validationResult.Errors);
                    return(ErrorResult(validationResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get Actor for current user by user name
                Actor createdBy       = null;
                var   currentUserName = command.CurrentPrincipal?
                                        .Identity?
                                        .Name;
                var creatorResponse = await Mediator
                                      .Send(new DbGetActorByNameRequest(currentUserName))
                                      .ConfigureAwait(false);

                if (creatorResponse.Success)
                {
                    createdBy = creatorResponse.Entity;
                }

                var entity = new _TEntity()
                {
                    CreatedAt   = DateTime.UtcNow,
                    CreatedBy   = createdBy,
                    Description = command.Description,
                    IsArchived  = command.IsArchived,
                    Title       = command.Title,
                    GeoJson     = command.GeoJson,
                    ProjectId   = command.ProjectId
                };

                var validatorBeforeSave        = new BeforeSaveValidator <_TEntity>();
                var validationBeforeSaveResult = await validatorBeforeSave
                                                 .ValidateAsync(entity).ConfigureAwait(false);

                if (!validationBeforeSaveResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestNotValid,
                                      "Geo validation error. Entity={Entity}. " +
                                      "Error={Error}.",
                                      entity.ToDictionary(),
                                      validationBeforeSaveResult.Errors);
                    return(ErrorResult(validationBeforeSaveResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get project role of current actor
                var projectResponse = await Mediator
                                      .Send(new DbGetEntityByIdRequest <Project>(entity.ProjectId))
                                      .ConfigureAwait(false);

                ActorRole currentProjectRole = null;
                if (projectResponse.Success)
                {
                    projectResponse.Entity.ProjectActorRoles
                    .TryGetValue(createdBy.Id, out currentProjectRole);
                }

                var checkPermissionResult = await CheckPermission(entity,
                                                                  createdBy, currentProjectRole)
                                            .ConfigureAwait(false);

                if (!checkPermissionResult.Success)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Geo Create permission error. " +
                                      "Entity={Entity}. CurrentActor={CurrentActor}." +
                                      "CurrentActorProjectRole={CurrentActorProjectRole}." +
                                      " Error={Error}.",
                                      entity.ToDictionary(), createdBy?.ToDictionary(),
                                      currentProjectRole.Name, checkPermissionResult.Errors);
                    return(checkPermissionResult);
                }

                return(await Mediator
                       .Send(new DbCreateCommand <_TEntity>(entity))
                       .ConfigureAwait(false));
            }
            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Call repository exception");
                return(ErrorResult("Not found"));
            }
        }
Exemple #27
0
 public void RegisterFocusTransform(ActorRole role, Transform transform)
 {
     ref Transform arraySlot = ref focusTransforms[(int)role];
        public async Task <DeleteResult> Handle
            (DeleteCommand <_EntityType> command,
            CancellationToken cancellationToken)
        {
            if (command is null)
            {
                Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                  "Entity Delete empty command");
                return(ErrorResult("Entity Delete empty command"));
            }

            try
            {
                var validator        = new DeleteCommandValidator <_EntityType>();
                var validationResult = await validator.ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Validation command error. Command={Command}. " +
                                      "Error={Error}.",
                                      command.ToDictionary(), validationResult.Errors);
                    return(ErrorResult
                               (validationResult.Errors.Select(x => x.ErrorMessage)));
                }

                var entityResponse = await Mediator
                                     .Send(new DbGetEntityByIdRequest <_EntityType>(command.Id))
                                     .ConfigureAwait(false);

                if (entityResponse.Success != true)
                {
                    Logger.LogWarning(AppLogEvent.HandleNullResponse,
                                      "Handle Entity Delete Command " +
                                      "can not get the entity. " +
                                      "Command={Command}. Error={Error}.",
                                      command.ToDictionary(), entityResponse.Errors);
                    return(ErrorResult(entityResponse.Errors));
                }
                var entity = entityResponse.Entity;

                // Get Actor for current user by user name
                var currentActorResponse = await Mediator
                                           .Send(new DbGetActorByNameRequest
                                                 (command.CurrentPrincipal?.Identity?.Name))
                                           .ConfigureAwait(false);

                Actor currentActor = null;
                if (currentActorResponse.Success)
                {
                    currentActor = currentActorResponse.Entity;
                }

                // Get project role of current actor
                var projectResponse = await Mediator
                                      .Send(new DbGetEntityByIdRequest <Project>(entity.ProjectId))
                                      .ConfigureAwait(false);

                ActorRole currentProjectRole = null;
                if (projectResponse.Success)
                {
                    projectResponse.Entity.ProjectActorRoles
                    .TryGetValue(currentActor.Id, out currentProjectRole);
                }

                var checkPermissionResult = await CheckPermission(entity,
                                                                  currentActor, command.HardMode, currentProjectRole)
                                            .ConfigureAwait(false);

                if (!checkPermissionResult.Success)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Entity Delete permission not passed. " +
                                      "Entity={Entity}. CurrentActor={CurrentActor}. " +
                                      "CurrentActorProjectRole={CurrentActorProjectRole}" +
                                      "Error={Error}.",
                                      entity.ToDictionary(), currentActor?.ToDictionary(),
                                      currentProjectRole.Name, checkPermissionResult.Errors);
                    return(checkPermissionResult);
                }

                if (command.HardMode)
                {
                    await Mediator.Publish
                        (new BeforeEntityDelete <_EntityType>(entity))
                    .ConfigureAwait(false);

                    var result = await HardDelete(command, entity)
                                 .ConfigureAwait(false);

                    await Mediator.Publish
                        (new AfterEntityDelete <_EntityType>(entity))
                    .ConfigureAwait(false);

                    return(result);
                }
                else
                {
                    return(await SoftDelete(entity)
                           .ConfigureAwait(false));
                }
            }
            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Call repository exception");
                return(ErrorResult("Not found"));
            }
        }