public CrudMessage(CrudAction anAction, TKey aKey, TValue aValue, IActor sender) { Action = anAction; Key = aKey; Value = aValue; Sender = sender; }
/// <summary> /// Generate the view to be display to the user /// </summary> /// <param name="view">The name of the view to render</param> /// <param name="model">The model with the data to display</param> /// <param name="commitAction">The action to be invoked when the user desired save the changes made</param> /// <returns>The task to be invoked</returns> private async Task <IActionResult> RenderView( string view, IViewModel model, CrudAction commitAction = null) { Task <string> contentTask; if (Settings.UseModals) { var popupModel = new Popup() { Model = model, InnerView = view, CommitAction = commitAction }; contentTask = _renderingService.RenderToStringAsync("_popup", popupModel, ViewData); } else { contentTask = _renderingService.RenderToStringAsync(view, model, ViewData); } return(Content(await contentTask, "text/html")); }
private int ExecuteNonQuery(CrudAction crudAction, T entity) { if (entity == null) { return(0); } using (SqlCommand command = new SqlCommand()) { #if DEBUG Stopwatch timer = new Stopwatch(); timer.Start(); #endif try { commandBuilder.BuildSqlCommand(command, entity, crudAction); return(command.ExecuteNonQuery()); } catch { } finally { command.Connection.Close(); #if DEBUG timer.Stop(); SqlCommandBuilder.PrintCommand(command); Debug.Write($"took {timer.Elapsed.Minutes}:{timer.Elapsed.Seconds}:{timer.Elapsed.Milliseconds}"); #endif } } return(0); }
private IQueryable <T> ExecuteReader(Func <T, bool> criteria, CrudAction crudAction) { using (SqlCommand command = new SqlCommand()) { #if DEBUG Stopwatch timer = new Stopwatch(); timer.Start(); #endif try { commandBuilder.BuildSqlCommand(command, criteria, crudAction); using (SqlDataReader reader = command.ExecuteReader()) { IEnumerable <T> entities = this.dataMapper.MapDataToEntities <T>(reader).ToList(); return((entities?.Count() ?? 0) > 0 ? entities.ToList().AsQueryable() : null); } } catch (Exception ex) { Debug.Write("Exception: " + ex.Message); } finally { command.Connection.Close(); #if DEBUG timer.Stop(); SqlCommandBuilder.PrintCommand(command); Debug.Write($"took {timer.Elapsed.Minutes}:{timer.Elapsed.Seconds}:{timer.Elapsed.Milliseconds}"); #endif } } return(null); }
internal ServiceResult?BeforeAction(CrudAction arg1, Model?_) { if (arg1.HasFlag(CrudAction.Commit)) { _stopwatch.Restart(); } return(null); }
public override IEnumerable <string> Validate(Employee entity, CrudAction action) { var errors = new List <string>(); switch (action) { case CrudAction.Create: if (GenerateCreateError) { errors.Add("CREATE ERROR"); } if (base.List.Any(i => i.ID == entity.ID && !Tools.Object.Compare(i, entity))) { errors.Add("ID is already in use"); } if (entity.ID < 0) { errors.Add("ID cannot be negative"); } if (entity.DateOfBirth == DateTime.MinValue) { errors.Add("DOB has not been set"); } break; case CrudAction.Update: if (GenerateUpdateError) { errors.Add("UPDATE ERROR"); } if (entity.ID < 0) { errors.Add("ID cannot be negative"); } if (entity.DateOfBirth == DateTime.MinValue) { errors.Add("DOB has not been set"); } break; case CrudAction.Delete: if (GenerateDeleteError) { errors.Add("DELETE ERROR"); } break; } return(errors); }
private CommandDefinition GetStoredProcedureConfiguration(string entityName, CrudAction crudAction) { var entityConfiguration = sqlMapperConfigurationSection?.Value?.FirstOrDefault(m => string.Equals(entityName, m.Name, StringComparison.OrdinalIgnoreCase)); if (entityConfiguration == null) { return(null); } CommandDefinition storedProcedureConfiguration = entityConfiguration.CommandName(crudAction); return(storedProcedureConfiguration); }
public void Perform(CrudAction action) { switch (action) { case CrudAction.Add: new AddAction().Perform(); break; case CrudAction.Get: new GetAction().Perform(); break; case CrudAction.Update: new UpdateAction().Perform(); break; default: throw new ArgumentException(); } }
private void SaveAudit(IEnumerable <PropertyValueTracker> entity, CrudAction changeType) { var audit = new DataAudit() { ChangedBy = currentUserService.GetCurrentUserInfo()?.NetworkID, ChangedDate = DateTime.Now, ChangeType = (int)changeType, EntityName = entity.GetType().FullName, NewInfo = entity.ToXMLString() }; repository.Save(audit); }
public static async Task UpdateSearchIndex <T>(T entityToUpdate, CrudAction action) where T : Entity, new() { if (_updateSearchService) { if (entityToUpdate is ISearcheable searchable) { var indexObject = searchable.GetIndexObject(); if (indexObject != null) { var targetType = typeof(T).Name.ToLower(); try { StringResponse response; switch (action) { case CrudAction.Create: { indexObject.CreatedAt = DateTime.Now; response = await _lowlevelClient.IndexAsync <StringResponse>(targetType, targetType, indexObject.Id, PostData.Serializable(indexObject)); } break; case CrudAction.Update: { indexObject.UpdatedAt = DateTime.Now; response = await _lowlevelClient.IndexPutAsync <StringResponse>(targetType, targetType, indexObject.Id, PostData.Serializable(indexObject)); break; } case CrudAction.Delete: { response = await _lowlevelClient.DeleteAsync <StringResponse>(targetType, targetType, indexObject.Id); break; } } } catch (Exception e) { } } } } }
internal ServiceResult?AfterAction(CrudAction arg1, Model?_) { if (arg1.HasFlag(CrudAction.Commit)) { _stopwatch.Stop(); Elapsed?.Invoke(this, _stopwatch.Elapsed.TotalMilliseconds.PushInto(_events)); Notify(nameof(EventCount)); Notify(nameof(AverageMs)); Notify(nameof(MinMs)); Notify(nameof(MaxMs)); } return(null); }
public bool Validate(CrudAction action) { const int rtfHeightPerLine = 20; const int maxErrorsWithoutScrollbar = 5; var errors = _dataSource.Validate(action != CrudAction.Delete ? _crudEntityEditor.GetEntityWithChanges() : _entity, action); var extraHeight = rtfHeightPerLine * errors.Count().ClipTo(0, maxErrorsWithoutScrollbar) - _tableLayoutPanel.RowStyles[1].Height; this.Size = new Size(this.Size.Width, (int)(this.Size.Height + extraHeight)); _tableLayoutPanel.RowStyles[1].Height = (_tableLayoutPanel.RowStyles[1].Height + extraHeight).ClipTo(0.0f, float.MaxValue); if (errors.Any()) { _errorRichTextBox.Lines = errors.ToArray(); return(false); } return(true); }
public override int GetHashCode() { int hash = 1; if (JWToken.Length != 0) { hash ^= JWToken.GetHashCode(); } if (CrudAction != 0) { hash ^= CrudAction.GetHashCode(); } if (roomType_ != null) { hash ^= RoomType.GetHashCode(); } return(hash); }
public void BuildSqlCommand(SqlCommand command, IBaseModel newEntity, CrudAction crudAction) { if (command == null || newEntity == null) { return; } var entityType = newEntity.GetType(); var entityName = entityType.FullName; CommandDefinition commandDefinition = GetStoredProcedureConfiguration(entityName, crudAction); SetCommandText(commandDefinition, command, newEntity, crudAction); SetCommandType(commandDefinition, command); AddParameters(commandDefinition, command, newEntity, crudAction); SetupConnection(commandDefinition, command); }
public CommandDefinition CommandName(CrudAction crudAction) { CommandDefinition commandDefinition = null; if (crudAction == CrudAction.Select) { commandDefinition = this.Select; } if (crudAction == CrudAction.Delete) { commandDefinition = this.Delete; } if (crudAction == CrudAction.Insert) { commandDefinition = this.Insert; } if (crudAction == CrudAction.Update) { commandDefinition = this.Update; } if (commandDefinition != null) { return(commandDefinition); } if (Crud != null) { commandDefinition = this.Crud; } if (commandDefinition != null) { return(commandDefinition); } return(null); }
public override int GetHashCode() { int hash = 1; if (JWToken.Length != 0) { hash ^= JWToken.GetHashCode(); } if (CrudAction != 0) { hash ^= CrudAction.GetHashCode(); } if (before_ != null) { hash ^= Before.GetHashCode(); } if (after_ != null) { hash ^= After.GetHashCode(); } return(hash); }
private async Task <SimpleResponse> CrudAsync(TEntity entity, CrudAction action, Action <Exception, string> errorLog = null, string summary = null) { int result = 0; var response = new SimpleResponse(); try { if (action == CrudAction.Insert) { await dbSet.AddAsync(entity); } else if (action == CrudAction.Update) { dbSet.Update(entity); } else if (action == CrudAction.Delete) { dbSet.Remove(entity); } result = await context.SaveChangesAsync(); if (result > 0) { response.Status = DbQueryStatus.Success; } } catch (DbUpdateException dbEx) { response.Message = dbEx.Message; errorLog?.Invoke(dbEx, summary); } catch (Exception ex) { response.Message = ex.Message; errorLog?.Invoke(ex, summary); } return(response); }
public string GetServiceUrl(object criteria, CrudAction crudAction) { var entityName = criteria?.GetType()?.FullName; if (string.IsNullOrWhiteSpace(entityName)) { return(string.Empty); } var odataCriteria = criteria as IODataCriteria; ODataDefinition definition = GetODataDefinition(entityName, crudAction); var connetionString = !string.IsNullOrWhiteSpace(definition?.ConnectionStringName) ? configuration.GetConnectionString(definition.ConnectionStringName) : null; if (!string.IsNullOrWhiteSpace(connetionString)) { var filter = odataCriteria.GetServiceUrl(); return(connetionString + (!string.IsNullOrWhiteSpace(filter) ? $"?$filter={filter}" : "")); } return(""); }
private Cell CreateCommandCell(ICrudGridColumn columnBinding, object entity, CrudAction action) { System.Drawing.Image image; Action <object> callback; switch (action) { case CrudAction.Update: image = Properties.Resources.SmallEditIcon; callback = EditEntity; break; case CrudAction.Delete: image = Properties.Resources.Cross; callback = DeleteEntity; break; case CrudAction.Create: default: throw new ArgumentException(string.Format("Invalid command '{0}'", action), "action"); } return(CreateButtonCell(columnBinding, entity, string.Empty, image, callback)); }
public ODataDefinition CommandName(CrudAction crudAction) { ODataDefinition commandDefinition = null; if (crudAction == CrudAction.Select) { commandDefinition = Select; } if (crudAction == CrudAction.Delete) { commandDefinition = Delete; } if (crudAction == CrudAction.Insert) { commandDefinition = Insert; } if (crudAction == CrudAction.Update) { commandDefinition = Update; } if (commandDefinition != null) { return(commandDefinition); } if (Crud != null) { commandDefinition = Crud; } return(commandDefinition); }
public CrudException(string tableName, CrudAction action, string message) : base(message) { this.tableName = tableName; this.action = action; }
public CrudException(string tableName, CrudAction action, int id, string message) : base(message) { this.tableName = tableName; this.action = action; this.recordId = id; }
public CrudException(string tableName, CrudAction action, int?id) { this.tableName = tableName; this.action = action; this.recordId = id; }
public static NotFoundResponse Create <T>(object identifier, CrudAction action) { return(Create(typeof(T), identifier, action)); }
private static NotFoundResponse Create(Type type, object id, CrudAction action) { string message = $"Could not {action.ToString().ToLower()} {type.Name.ToLower()} with id = {id}"; return(new (message)); }
public bool IsActionAllowed(CrudAction action) => _allowedActions?.Contains(action) ?? true;
public abstract IEnumerable <string> Validate(TEntity entity, CrudAction action);
private string GetCommandText(CommandDefinition commandDefinition, IBaseModel entityType, CrudAction crudAction) { var entityName = entityType?.GetType()?.Name; if (!string.IsNullOrWhiteSpace(commandDefinition?.Command) || !string.IsNullOrWhiteSpace(commandDefinition?.QueryFilePath)) { return(!string.IsNullOrWhiteSpace(commandDefinition.Command) ? commandDefinition.Command : fileService.GetFileContent(commandDefinition.QueryFilePath)); } string commandText = ""; var tableName = entityName?.Pluralize(); if (crudAction == CrudAction.Delete) { commandText = $"DELETE FROM {tableName}"; } else if (crudAction == CrudAction.Insert) { commandText = $"INSERT INTO {tableName}"; } else if (crudAction == CrudAction.Select) { commandText = $"SELECT * FROM {tableName}"; } else if (crudAction == CrudAction.Update) { commandText = $"UPDATE {tableName}"; } var parameters = GetPropertiesWithValues(entityType)?.ToList(); if (crudAction == CrudAction.Delete || crudAction == CrudAction.Select) { var whereClause = ""; if ((parameters?.Count ?? 0) > 0) { whereClause = string.Join(" AND ", parameters.Select(p => $"{p.Name} = @{p.Name}")); if ((whereClause?.Length ?? 0) > 0) { whereClause = $" WHERE {whereClause}"; } } commandText = $"{commandText} {whereClause}".Trim(); } else if (crudAction == CrudAction.Insert) { var parameterNames = string.Join(", ", parameters?.Select(p => $"@{p.Name}")?.ToList() ?? Enumerable.Empty <string>()); var columns = string.Join(", ", parameters?.Select(p => p.Name)?.ToList() ?? Enumerable.Empty <string>()); commandText = $"{commandText} ({columns}) VALUES ({parameterNames})"; var identityProperty = GetIdentityProperty(entityType)?.FirstOrDefault(); if (identityProperty != null) { commandText = $"{commandText} SELECT * FROM {tableName} WHERE {identityProperty.Name} = SCOPE_IDENTITY()"; } else { commandText = $"{commandText} {GetCommandText(commandDefinition, entityType, CrudAction.Select)}"; } } else if (crudAction == CrudAction.Update) { var primaryKeyColumnNames = GetPrimaryKeyProperties(entityType)?.Select(p => p.Name)?.ToArray(); var columnNames = entityType.GetPropertyNames()?.Where(c => Array.IndexOf(primaryKeyColumnNames, c) == -1)?.ToList(); var updateClause = string.Join(",", columnNames?.Select(c => $"{c} = {ParameterPrefix}{c}")?.ToList() ?? Enumerable.Empty <string>()); var whereClause = string.Join(",", primaryKeyColumnNames?.Select(c => $"{c} = {ParameterPrefix}{c}")?.ToList() ?? Enumerable.Empty <string>()); commandText = $"SET {updateClause} {whereClause}"; } return(commandText); }
private void SetCommandText(CommandDefinition commandDefinition, SqlCommand command, IBaseModel entityType, CrudAction crudAction) { var commandText = GetCommandText(commandDefinition, entityType, crudAction); if (string.IsNullOrWhiteSpace(commandText)) { return; } command.CommandText = commandText; }
private void AddParameters <T>(CommandDefinition commandDefinition, SqlCommand command, T newEntity, CrudAction crudAction) where T : IBaseModel { var entityName = newEntity.GetType().Name; var parameters = commandDefinition?.CommandType == CommandType.Text ? SetTextCommandParameters(command, newEntity) : GetParametersWithValues <T>(newEntity); if (parameters == null) { return; } command.Parameters.AddRange(parameters.ToArray()); }