private static void CreateUsers() { // cargar tiendas var stores = new StoreDataAccess().LoadAll(false); // cargar admin group var adminGroup = new GroupDataAccess().LoadAll(false)[0]; UserDataAccess uda = new UserDataAccess(); foreach (StoreEntity store in stores) { var ue = new UserEntity(); ue.Name = GetMaleName(); ue.Surname = GetLastName(); ue.UserName = GetUserName(ue.Name, ue.Surname); ue.IsUserActive = true; ue.Password = Utilities.CalculateHashString("123"); ue.PhoneNumber = GetPhoneNumber(); ue.Charge = "Administrador"; ue.Store = store; // add user group var ug = new UserGroupEntity(); ug.Group = adminGroup; ug.User = ue; ue.UserGroup.Add(ug); // save user uda.Save(ue); } }
/// <summary> /// Searches users. /// </summary> /// <param name="group">The user group entity.</param> /// <param name="role">The role to search; or null for all roles.</param> /// <param name="q">The optional name query; or null for all.</param> /// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param> /// <returns>The token entity matched if found; otherwise, null.</returns> public Task <IEnumerable <UserGroupRelationshipEntity> > ListUsersAsync(UserGroupEntity group, UserGroupRelationshipEntity.Roles?role, QueryArgs q, CancellationToken cancellationToken = default) { var col = relationships.Where(ele => ele.OwnerId == group?.Id); if (role.HasValue) { col = col.Where(ele => ele.Role == role.Value); } if (q != null) { q = InternalAssertion.DefaultQueryArgs; } if (!string.IsNullOrWhiteSpace(q.NameQuery)) { if (q.NameExactly) { col = col.Where(ele => ele.Name == q.NameQuery); } else { col = col.Where(ele => ele.Name.Contains(q.NameQuery)); } } return(ToListAsync(col.Where(ele => ele.State == q.State).Skip(q.Offset).Take(q.Count > 0 ? q.Count : ResourceEntityExtensions.PageSize), cancellationToken)); }
public async Task <UserGroupEntity> Update(UserGroupEntity usergroup) { var storedUserGroup = _usergroupRepository.GetByBoardId(usergroup.BoardId); foreach (var selectedUserGroup in storedUserGroup) { if (selectedUserGroup.UserId.Equals(usergroup.UserId)) { try { selectedUserGroup.IsAdministrator = usergroup.IsAdministrator; selectedUserGroup.Active = usergroup.Active; selectedUserGroup.UpdatedAt = DateTime.Now; var updatedUserGroup = await _usergroupRepository.Update(selectedUserGroup); return(updatedUserGroup); } catch (Exception error) { throw error; } } } throw new Exception("UserGroup not exists! Choice another name!"); }
private async Task AddGroupAsync(UserEntity proposalUser, UserEntity requiredUser) { UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == proposalUser.Id); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Id == requiredUser.Id); if (user == null) { userGroup.Users.Add(new UserGroupDetailEntity { User = requiredUser }); } _context.UserGroups.Update(userGroup); } else { _context.UserGroups.Add(new UserGroupEntity { User = proposalUser, Users = new List <UserGroupDetailEntity> { new UserGroupDetailEntity { User = requiredUser } } }); } }
private bool SaveUserGroup() { if (!CanSave()) { return(false); } UserGroupEntity UserGroup = new UserGroupEntity(); UserGroup.UserGroupCode = txtUserGroupCode.Text; UserGroup.UserGroupName = txtUserGroupName.Text; UserGroup.UserGroupID = new Guid(txtUserGroupCode.Tag.ToString()); if (UserGroup.UserGroupID == new Guid()) { UserGroup.UserGroupID = UserGroupData.Insert(UserGroup); UserGroupBS.Add(UserGroup); } else { UserGroupData.Update(UserGroup); CurrentUserGroup = UserGroup; } grdUserGroup.Refetch(); EnableItems(true); return(true); }
/// <summary>Creates a new, empty UserGroupEntity object.</summary> /// <returns>A new, empty UserGroupEntity object.</returns> public override IEntity Create() { IEntity toReturn = new UserGroupEntity(); // __LLBLGENPRO_USER_CODE_REGION_START CreateNewUserGroup // __LLBLGENPRO_USER_CODE_REGION_END return(toReturn); }
/// <summary> /// Gets a collection of user group permissions. /// </summary> /// <param name="group">The user group entity.</param> /// <param name="siteId">The site identifier.</param> /// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param> /// <returns>The permission entity matched if found; otherwise, null.</returns> public async Task <UserGroupPermissionItemEntity> GetGroupPermissionsAsync(UserGroupEntity group, string siteId, CancellationToken cancellationToken = default) { if (group == null) { return(null); } return(await GetContext(true).GroupPermissions.FirstOrDefaultAsync(ele => ele.TargetId == group.Id && ele.SiteId == siteId, cancellationToken)); }
private static UserGroupDto ToUserGroupDto(UserGroupEntity group) { UserGroupDto userGroupDto = new UserGroupDto(); userGroupDto.Id = group.Id; userGroupDto.Name = group.Name; return(userGroupDto); }
/// <summary> /// Método invocado cuando se hace click en el botón Aceptar. /// </summary> /// <param name="sender"> /// El objeto que genera el evento. /// </param> /// <param name="e"> /// Un objeto que contiene información acerca del evento. /// </param> private void OnOkClicked(object sender, RoutedEventArgs e) { System.Collections.Generic.List <UserGroupEntity> toRemove = new List <UserGroupEntity>(); // Agrega los grupos quitados a la lista. foreach (UserGroupEntity userGroup in user.UserGroup) { bool exists = false; foreach (GroupEntity group in Selected) { if (userGroup.Group.Name == group.Name) { exists = true; break; } } if (!exists) { toRemove.Add(userGroup); } } // Quitarlos. foreach (UserGroupEntity userGroup in toRemove) { user.UserGroup.Remove(userGroup); } // Agregar los nuevos grupos. foreach (GroupEntity group in Selected) { bool exists = false; foreach (UserGroupEntity userGroup in user.UserGroup) { if (userGroup.Group.Name == group.Name) { exists = true; break; } } if (!exists) { UserGroupEntity userGroup = new UserGroupEntity(); userGroup.Group = group; user.UserGroup.Add(userGroup); } } if (OkSelected != null) { OkSelected(sender, e); } }
public void AssignUserToGroup(int userId, int groupId) { var userGroup = new UserGroupEntity { GroupId = groupId, UserId = userId }; _db.UserGroups.Add(userGroup); SaveChanges(); }
/// <summary> /// Function to Load the relation Group from database. /// </summary> /// <param name="userGroup">UserGroupEntity parent</param> /// <exception cref="ArgumentNullException"> /// if <paramref name="userGroup"/> is not a <c>UserGroupEntity</c>. /// </exception> public void LoadRelationGroup(UserGroupEntity userGroup, Dictionary <string, IEntity> scope) { if (userGroup == null) { throw new ArgumentException("The argument can't be null"); } bool closeConnection = false; try { // Create a new connection if needed if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } // Create a command string cmdText = "SELECT idGroup FROM [UserGroup] WHERE idUserGroup = @idUserGroup"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idUserGroup", DbType.Int32); // Set command parameters values parameter.Value = userGroup.Id; sqlCommand.Parameters.Add(parameter); // Execute commands object idRelation = sqlCommand.ExecuteScalar(); if (idRelation != null && ((int)idRelation) > 0) { // Create data access objects and set connection objects GroupDataAccess groupDataAccess = new GroupDataAccess(); groupDataAccess.SetConnectionObjects(dbConnection, dbTransaction); // Load related object userGroup.Group = groupDataAccess.Load(((int)idRelation), true, scope); } } catch (DbException dbException) { // Catch and rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if initiated by me if (closeConnection) { dbConnection.Close(); } } }
public async Task <IActionResult> SaveGroupAsync([FromBody] UserGroupEntity entity) { if (entity == null) { return(ChangeErrorKinds.Argument.ToActionResult("Requires an entity in body.")); } var instance = await this.GetResourceAccessClientAsync(); var result = await instance.SaveAsync(entity); Logger?.LogInformation(new EventId(17001013, "SaveUserGroupInfo"), "Save user group information {0}.", entity.Name ?? entity.Id); return(result.ToActionResult()); }
public async Task <ResponseMessage> Update(UserGroupEntity usergroup) { try { var storedUserGroup = await _usergroupService.Update(usergroup); return(new ResponseMessage(true, storedUserGroup, "UserGroup updated with success!", HttpStatusCode.OK)); } catch (Exception err) { return(new ResponseMessage(false, null, err.Message, HttpStatusCode.BadRequest)); } }
private void FillSaveParameters(UserGroupEntity userGroup, IDbCommand sqlCommand) { IDbDataParameter parameter; parameter = dataAccess.GetNewDataParameter("@idGroup", DbType.Int32); parameter.Value = userGroup.IdGroup; sqlCommand.Parameters.Add(parameter); parameter = dataAccess.GetNewDataParameter("@idUser", DbType.Int32); parameter.Value = userGroup.IdUser; sqlCommand.Parameters.Add(parameter); }
/// <summary> /// Searches users. /// </summary> /// <param name="group">The user group entity.</param> /// <param name="role">The role to search; or null for all roles.</param> /// <param name="q">The optional name query; or null for all.</param> /// <param name="relationshipState">The relationship entity state.</param> /// <returns>The token entity matched if found; otherwise, null.</returns> public IEnumerable <UserGroupRelationshipEntity> ListUsers(UserGroupEntity group, UserGroupRelationshipEntity.Roles?role = null, string q = null, ResourceEntityStates relationshipState = ResourceEntityStates.Normal) { var col = relationships.Where(ele => ele.OwnerId == group?.Id && ele.State == relationshipState); if (role.HasValue) { col = col.Where(ele => ele.Role == role.Value); } if (!string.IsNullOrWhiteSpace(q)) { col = col.Where(ele => ele.Name.Contains(q)); } return(col); }
public async Task <UserGroupEntity> Add(UserGroupEntity usergroup) { try { _context.UserGroups.Add(usergroup); await _context.SaveChangesAsync(); return(usergroup); } catch (Exception error) { throw error; } }
private static bool ValidateUserGroup(Collection <UserGroupEntity> UserGroup) { bool result = true; for (int i = 0; i < UserGroup.Count; i++) { UserGroupEntity item = UserGroup[i]; if (item.Group == null) { item.Errors.Add(new Error("Group", "Group", "El grupo no puede estar vacío")); result = false; } } return(result); }
void UserGroupBS_PositionChanged(object sender, EventArgs e) { EmptyFields(); CurrentUserGroup = new UserGroupEntity(); if (UserGroupBS.Count == 0) { return; } CurrentUserGroup = (UserGroupEntity)UserGroupBS.Current; txtUserGroupName.Text = CurrentUserGroup.UserGroupName; txtUserGroupCode.Text = CurrentUserGroup.UserGroupCode; txtUserGroupCode.Tag = CurrentUserGroup.UserGroupID; }
/// <summary> /// Searches users. /// </summary> /// <param name="group">The user group entity.</param> /// <param name="role">The role to search; or null for all roles.</param> /// <param name="q">The optional name query; or null for all.</param> /// <param name="relationshipState">The relationship entity state.</param> /// <returns>The token entity matched if found; otherwise, null.</returns> public IQueryable <UserGroupRelationshipEntity> ListUsers(UserGroupEntity group, UserGroupRelationshipEntity.Roles?role = null, string q = null, ResourceEntityStates relationshipState = ResourceEntityStates.Normal) { var context = GetContext(true); var users = string.IsNullOrWhiteSpace(q) ? context.Users.Where(ele => ele.StateCode == ResourceEntityExtensions.NormalStateCode) : context.Users.Where(ele => (ele.Name.Contains(q) || (ele.Nickname != null && ele.Nickname.Contains(q))) && ele.StateCode == ResourceEntityExtensions.NormalStateCode); var relationships = context.Relationships.Where(ele => ele.OwnerId == group.Id && ele.StateCode == (int)relationshipState); if (role.HasValue) { relationships = relationships.Where(ele => ele.RoleCode == (int)role.Value); } return(relationships.Join( users, ele => ele.OwnerId, ele => ele.Id, (rela, user) => new UserGroupRelationshipEntity(rela, group, user))); }
public async Task <IActionResult> GetUserGroup([FromRoute] string id) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserGroupEntity userGroup = await _context.UserGroupEntities .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(u => u.User.Id == id); if (userGroup == null || userGroup?.Users == null) { return(Ok()); } return(Ok(_converterHelper.ToUserGroupResponse(userGroup.Users.ToList()))); }
public async Task <IActionResult> AssociateUser(Guid groupId) { using SqlConnection connection = this.userService.Connection; UserEntity user = await this.userDatabaseAccess.Get(this.userService.Username, connection); DateTime now = DateTime.Now; UserGroupEntity userGroup = new UserGroupEntity() { CreationDate = now, GroupId = groupId, UserId = user.Id }; using DatabaseContext context = new DatabaseContext(connection); await context.UserGroup.AddAsync(userGroup); await context.SaveChangesAsync(); return(this.Ok()); }
public async Task <UserGroupEntity> Add(UserGroupEntity usergroup) { var storedBoard = _boardRepository.GetById(usergroup.BoardId); if (storedBoard != null) { try { var saveUserGroup = await _usergroupRepository.Add(usergroup); storedBoard.UserGroups.Add(usergroup); var saveBoardUserGroup = await _boardRepository.Update(storedBoard); return(saveUserGroup); } catch (Exception error) { throw error; } } throw new Exception("Board not exists! Choice another name!"); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest("Este Usuario no existe.")); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest("Este Usuario no existe.")); } UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest("Este Usuario ya pertenece al Grupo.")); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequests.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail(request.Email, "Solicitud de unirse a un Grupo", $"<h1>Solicitud de unirse a un Grupo</h1>" + $"El Usuario: {proposalUser.FullName} ({proposalUser.Email}), ha solicitado que sea miembro de su grupo de usuarios en la aplicación TAXI." + $"</hr></br></br>Si desea aceptar, haga clic aquí: <a href = \"{linkConfirm}\">Confirmar</a>" + $"</hr></br></br>Si desea rechazar, haga clic aquí: <a href = \"{linkReject}\">Rechazar</a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok("Se ha enviado un correo electrónico al usuario con su solicitud, esperamos a que responda pronto!")); }
public Task <UserGroupEntity> Update(UserGroupEntity usergroup) { throw new NotImplementedException(); }
/// <summary> /// Function to load a UserGroupEntity from database. /// </summary> /// <param name="id">The ID of the record to load</param> /// <param name="loadRelation">if is true load the relation</param> /// <param name="scope">Internal structure used to avoid circular reference locks, must be provided if calling from other data access object</param> /// <returns>The entity instance</returns> /// <exception cref="UtnEmallDataAccessException"> /// If a DbException occurs while accessing the database. /// </exception> public UserGroupEntity Load(int id, bool loadRelation, Dictionary <string, IEntity> scope) { // Build a key for internal scope object string scopeKey = id.ToString(NumberFormatInfo.InvariantInfo) + "UserGroup"; if (scope != null) { // If scope contains the object it was already loaded, // return it to avoid circular references if (scope.ContainsKey(scopeKey)) { return((UserGroupEntity)scope[scopeKey]); } } else { // If there isn't a current scope create one scope = new Dictionary <string, IEntity>(); } UserGroupEntity userGroup = null; // Check if the entity was already loaded by current data access object // and return it if that is the case if (inMemoryEntities.ContainsKey(id)) { userGroup = inMemoryEntities[id]; // Add current object to current load scope scope.Add(scopeKey, userGroup); } else { bool closeConnection = false; try { // Open a new connection if it isn't on a transaction if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0) { closeConnection = true; dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); } string cmdText = "SELECT idUserGroup, idGroup, idUser, timestamp FROM [UserGroup] WHERE idUserGroup = @idUserGroup"; // Create the command IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); // Create the Id parameter for the query IDbDataParameter parameter = dataAccess.GetNewDataParameter("@idUserGroup", DbType.Int32); parameter.Value = id; sqlCommand.Parameters.Add(parameter); // Use a DataReader to get data from db IDataReader reader = sqlCommand.ExecuteReader(); userGroup = new UserGroupEntity(); if (reader.Read()) { // Load fields of entity userGroup.Id = reader.GetInt32(0); userGroup.IdGroup = reader.GetInt32(1); userGroup.IdUser = reader.GetInt32(2); // Add current object to the scope scope.Add(scopeKey, userGroup); // Add current object to cache of loaded entities inMemoryEntities.Add(userGroup.Id, userGroup); // Read the timestamp and set new and changed properties userGroup.Timestamp = reader.GetDateTime(3); userGroup.IsNew = false; userGroup.Changed = false; // Close the reader reader.Close(); // Load related objects if required if (loadRelation) { LoadRelationGroup(userGroup, scope); } } else { reader.Close(); } } catch (DbException dbException) { // Catch DBException and rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if it was opened by ourself if (closeConnection) { dbConnection.Close(); } } } // Return the loaded entity return(userGroup); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } CultureInfo cultureInfo = new CultureInfo(request.CultureInfo); Resource.Culture = cultureInfo; UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest(Resource.UserNotFoundError)); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest(Resource.UserNotFoundError)); } UserGroupEntity userGroup = await _context.UserGroupEntities .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest(Resource.UserAlreadyBelogToGroup)); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequestEntities.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail(request.Email, Resource.RequestJoinGroupSubject, $"<h1>{Resource.RequestJoinGroupSubject}</h1>" + $"{Resource.TheUser}: {proposalUser.FullName} ({proposalUser.Email}), {Resource.RequestJoinGroupBody}" + $"</hr></br></br>{Resource.WishToAccept} <a href = \"{linkConfirm}\">{Resource.Confirm}</a>" + $"</hr></br></br>{Resource.WishToReject} <a href = \"{linkReject}\">{Resource.Reject}</a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok(Resource.RequestJoinGroupEmailSent)); }
public async Task <UserGroupEntity> Add(UserGroupEntity usergroup) { return(await _usergroupService.Add(usergroup)); }
public async Task <UserGroupEntity> Update(UserGroupEntity usergroup) { return(await _usergroupService.Update(usergroup)); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest()); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest()); } UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest()); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequests.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail(request.Email, "user request", $"<h1>{"User group"}</h1>" + $"{"convert user helper"}: {proposalUser.FullName} ({proposalUser.Email}), {"passs body"}" + $"</hr></br></br>{"Sccept"} <a href = \"{linkConfirm}\">{"Confirm"}</a>" + $"</hr></br></br>{"in join"} <a href = \"{linkReject}\">{"Reject"}</a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok()); }
/// <summary> /// Function to Delete a UserGroupEntity from database. /// </summary> /// <param name="userGroup">UserGroupEntity to delete</param> /// <param name="scope">Internal structure to avoid circular reference locks. Must provide an instance while calling from other data access object.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="userGroup"/> is not a <c>UserGroupEntity</c>. /// </exception> /// <exception cref="UtnEmallDataAccessException"> /// If an DbException occurs in the try block while accessing the database. /// </exception> public void Delete(UserGroupEntity userGroup, Dictionary <string, IEntity> scope) { if (userGroup == null) { throw new ArgumentException("The argument can't be null"); } try { // Open connection and initialize a transaction if needed if (!isGlobalTransaction) { dbConnection = dataAccess.GetNewConnection(); dbConnection.Open(); dbTransaction = dbConnection.BeginTransaction(); } // Reload the entity to ensure deletion of older data userGroup = this.Load(userGroup.Id, true); if (userGroup == null) { throw new UtnEmallDataAccessException("Error retrieving data while trying to delete."); } // Create a command for delete string cmdText = "DeleteUserGroup"; IDbCommand sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction); sqlCommand.CommandType = CommandType.StoredProcedure; // Add values to parameters IDbDataParameter parameterID = dataAccess.GetNewDataParameter("@idUserGroup", DbType.Int32); parameterID.Value = userGroup.Id; sqlCommand.Parameters.Add(parameterID); // Execute the command sqlCommand.ExecuteNonQuery(); // Delete related objects // Commit transaction if is mine if (!isGlobalTransaction) { dbTransaction.Commit(); } // Remove entity from loaded objects inMemoryEntities.Remove(userGroup.Id); // Remove entity from current internal scope if (scope != null) { string scopeKey = userGroup.Id.ToString(NumberFormatInfo.InvariantInfo) + "UserGroup"; scope.Remove(scopeKey); } } catch (DbException dbException) { // Rollback transaction if (!isGlobalTransaction) { dbTransaction.Rollback(); } // Rethrow as custom exception throw new UtnEmallDataAccessException(dbException.Message, dbException); } finally { // Close connection if it was initiated by this instance if (!isGlobalTransaction) { dbConnection.Close(); dbConnection = null; dbTransaction = null; } } }