Skip to content

Commit

Permalink
improvements to controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
clarkis117 committed Aug 21, 2016
1 parent 540f8b2 commit 09ecc8a
Show file tree
Hide file tree
Showing 6 changed files with 181 additions and 118 deletions.
26 changes: 6 additions & 20 deletions src/GenericMvcUtilities/Controllers/BaseApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,33 +56,19 @@ public BaseApiController(IRepository<T> repository, ILogger<T> logger)
}
}

/*
/// <summary>
/// Matches the by identifier expression.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
[NonAction]
public Expression<Func<IModel<TKey>, bool>> MatchByIdExpression(object id)
{
var parameterExpression = Expression.Parameter(typeof(IModel<TKey>));
var propertyOrField = Expression.PropertyOrField(parameterExpression, "Id");
var binaryExpression = Expression.Equal(propertyOrField, Expression.Constant(id));
return Expression.Lambda<Func<IModel<TKey>, bool>>(binaryExpression, parameterExpression);
}
*/

protected static readonly Type typeOfT = typeof(T);

[NonAction]
protected string FormatLogMessage(string message, Microsoft.AspNetCore.Http.HttpRequest request)
protected static string FormatLogMessage(string message, Microsoft.AspNetCore.Http.HttpRequest request)
{
return (message + ": \nHTTP Request: \n" + "Header: " + request.Headers.ToString() + "\nBody: " + request.Body.ToString());
}

//Todo: revamp this hardcore
[NonAction]
protected string FormatExceptionMessage(string message)
protected static string FormatExceptionMessage(string message)
{
return (this.GetType().Name + ": " + message + ": " + typeof(T));
return (this.GetType().Name + ": " + message + ": " + typeOfT.Name);
}

[NonAction]
Expand Down Expand Up @@ -347,7 +333,7 @@ public virtual async Task<IActionResult> Update(TKey id, [FromBody] T item)
var exists = await Repository.Any(x => x.Id.Equals(id));

//If Item Exists Update it
if (exists == true)
if (exists)
{
var updatedItem = await Repository.Update(item);

Expand Down
143 changes: 122 additions & 21 deletions src/GenericMvcUtilities/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public enum Message
ItemIsNotValidAndChangesHaveNotBeenSaved,
ErrorProcessingRequest,

RequestOrQueryIsInvalid,
ErrorExecutingQuery,
InvalidQuery
}
Expand All @@ -40,7 +41,7 @@ public abstract class BaseController<TKey, T> : Controller

protected static Microsoft.EntityFrameworkCore.Metadata.IEntityType DataModel;


protected static readonly Type typeOfT = typeof(T);

public BaseController(IEntityRepository<T> repository, ILogger<T> logger)
{
Expand Down Expand Up @@ -93,7 +94,120 @@ protected static string FormatLogMessage(string message, Microsoft.AspNetCore.Ht
[NonAction]
protected static string FormatExceptionMessage(Controller controller, string message)
{
return (controller.GetType().ToString() + ": " + message + ": " + typeof(T).ToString());
return (controller.GetType().Name + ": " + message + ": " + typeOfT.Name);
}

[NonAction]
public static MessageViewModel GetMessageFromEnum(Message? message)
{
if (message != null)
{
MessageViewModel messageViewModel = null;

switch (message.Value)
{
case Message.ItemHasBeenCreated:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Success,
Text = "Item has been successfully created"
};
break;
case Message.ItemHasBeenEdited:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Success,
Text = "Item has been successfully edited"
};
break;
case Message.ItemHasBeenRetrived:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Success,
Text = "Item has been successfully retrieved"
};
break;
case Message.ItemHasBeenDeleted:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Success,
Text = "Item has been successfully deleted"
};
break;
case Message.ItemNotFound:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Warning,
Text = "System was unable to find the Item"
};
break;
case Message.ItemCouldNotBeCreated:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "System was not able to save the new Item"
};
break;
case Message.ItemCouldNotBeEdited:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "System was not able to save the changes to the Item"
};
break;
case Message.ItemCouldNotBeRetrived:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "System could not retrieve the item"
};
break;
case Message.ItemIsNotValidAndChangesHaveNotBeenSaved:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Warning,
Text = "The current Item is not valid and any changes have not been saved"
};
break;
case Message.ErrorProcessingRequest:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "System encountered an error processing the request"
};
break;
case Message.ErrorExecutingQuery:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "System encountered an error executing the query"
};
break;
case Message.InvalidQuery:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Warning,
Text = "The specified query is not valid"
};
break;
case Message.RequestOrQueryIsInvalid:
messageViewModel = new MessageViewModel()
{
MessageType = MessageType.Warning,
Text = "The Specified Request or Query is not valid"
};
break;
default:
messageViewModel = new MessageViewModel();
break;
}

return messageViewModel;
}
else
{
return new MessageViewModel();
}
}

[NonAction]
Expand Down Expand Up @@ -124,31 +238,18 @@ public IEnumerable<SelectListItem> GetSearchSelectList()
[Route("[controller]/[action]/"), HttpGet]
public virtual async Task<IActionResult> Index(Message? message)
{
/*
var error = Error == SearchErrorMessages.InvalidQuery ?
new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "Invalid Search Query, use another query and try again"
}
: Error == SearchErrorMessages.ErrorExecutingQuery ?
new MessageViewModel()
{
MessageType = MessageType.Danger,
Text = "An Error occurred while executing the query, please try a different query"
}
: null;
*/
try
{
var messageViewModel = GetMessageFromEnum(message);

var results = await Repository.GetAll();

var indexViewModel = new IndexViewModel(this)
{
Data = results,
Count = results.LongCount(),
//Message = error ?? new MessageViewModel(),
DisplayingCount = results.LongCount(),
TotalCount = await Repository.Count(),
Message = messageViewModel ?? new MessageViewModel(),
SearchViewModel = new SearchViewModel()
{
SelectPropertyList = GetSearchSelectList()
Expand Down Expand Up @@ -191,7 +292,7 @@ public virtual async Task<IActionResult> Search([FromQuery] string PropertyName,
Action = "Index",
NestedView = "Index",
Data = results,
Count = results.LongCount(),
DisplayingCount = results.LongCount(),
Description = "Search Results for Query",
Message = new MessageViewModel(),
SearchViewModel = new SearchViewModel()
Expand Down
61 changes: 24 additions & 37 deletions src/GenericMvcUtilities/Controllers/BasicController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,33 +43,6 @@ public BasicController(IEntityRepository<T> repository, ILogger<T> logger) : bas
}
}

/*
// GET: /<controller>/
[Route("[controller]/[action]/")]
[HttpGet]
public virtual async Task<IActionResult> Index()
{
try
{
var indexViewModel = new IndexViewModel(this)
{
Data = await Repository.GetAll()
};
//return view
return this.ViewFromModel(indexViewModel);
}
catch (Exception ex)
{
string Message = "Get All / Index Failed";
Logger.LogError(FormatLogMessage(Message, this.Request), ex);
throw new Exception(FormatExceptionMessage(this,Message), ex);
}
}
*/

[Route("[controller]/[action]/"), HttpGet("{id}")]
public virtual async Task<IActionResult> Details(TKey id, Message? message)
{
Expand All @@ -92,12 +65,12 @@ public virtual async Task<IActionResult> Details(TKey id, Message? message)
else
{
//return NotFound();
return RedirectToAction(nameof(this.Index));
return RedirectToAction(nameof(this.Index), new { message = Message.ItemNotFound});
}
}
else
{
return BadRequest();
return RedirectToAction(nameof(this.Index), new { message = Message.ErrorProcessingRequest});
}
}
catch (Exception ex)
Expand All @@ -115,7 +88,7 @@ public virtual async Task<IActionResult> Edit(TKey id, Message? message)
{
try
{
if (id != null)
if (id != null && ModelState.IsValid)
{
var item = await Repository.Get(Repository.MatchByIdExpression(id));

Expand All @@ -132,12 +105,12 @@ public virtual async Task<IActionResult> Edit(TKey id, Message? message)
else
{
//httpnotfound
return RedirectToAction(nameof(this.Index));
return RedirectToAction(nameof(this.Index), new { message = Message.ItemNotFound});
}
}
else
{
return BadRequest();
return RedirectToAction(nameof(this.Index), new { message = Message.ErrorProcessingRequest });
}
}
catch (Exception ex)
Expand All @@ -164,7 +137,7 @@ public virtual async Task<IActionResult> Edit(T item)

if (updatedItem != null)
{
return RedirectToAction(nameof(this.Index));
return RedirectToAction(nameof(this.Index), new { message = Message.ItemHasBeenEdited});
}
else
{
Expand Down Expand Up @@ -216,29 +189,43 @@ public virtual IActionResult Create(Message? message)
}
}

[NonAction]
protected static IActionResult GetCreateViewModel(Controller controller, T item, Message message)
{
var createViewModel = new CreateViewModel(controller)
{
Data = item,
Message = GetMessageFromEnum(message)
};

return ViewModelHelper.ViewFromModel(controller, createViewModel);
}

[Route("[controller]/[action]/"), HttpPost, ValidateAntiForgeryToken]
public virtual async Task<IActionResult> Create(T item)
{
try
{
if (ModelState.IsValid && item != null)
if (item != null && ModelState.IsValid)
{
var createdItem = await Repository.Create(item);

if (createdItem != null)
{
return RedirectToAction(nameof(this.Index));
return RedirectToAction(nameof(this.Index), new { message = Message.ItemHasBeenCreated});
}
else
{
//Send 500 Response if update fails
throw new Exception("Creating Item Failed");
//throw new Exception("Creating Item Failed");
return GetCreateViewModel(this, item, Message.ItemCouldNotBeCreated);
}
}
else
{
//send bad request response with model state errors
return BadRequest(ModelState);
//return BadRequest(ModelState);
return GetCreateViewModel(this, item, Message.ItemIsNotValidAndChangesHaveNotBeenSaved);
}
}
catch (Exception ex)
Expand Down
Loading

0 comments on commit 09ecc8a

Please sign in to comment.