I am moving 1 project, just the data tier, the project is using MVC 1.0 and acess mdb :S
Now I am moving to SubSonic + Sql server and all is fine, except when I try to implement to my class IDataErrorInfo for validation messages, I get always 2 times every error message
I have a table class generated by subsonic:MyTable, then I extend it.
public partial class myTable : IDataErrorInfo{
public string this[string columnName]{
get{
switch (columnName.ToUpperInvariant()){
case "MYFIELD":
if (string.IsNullOrEmpty(myField)){
return "Incorrect MyField";
}
break;
case "ANOTHER":
if (string.IsNullOrEmpty(myField)){
return "Incorrect Another";
}
break;
}
return "";
}
}
public string Error{
get{
return "";
}
}
}
In My Controller I add to my post action this code:
public class mycontroller...{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult myAction(int id, MyTable data)
{
try
{
UpdateModel(data, new[] { "MyField","Another" });
data.Save();
return RedirectToAction("Admin");
}
catch (Exception ex)
{
//ViewData["Error"] = ex.Message;
return View(data);
}
}
My view have a summary generated as Html.ValidationSummary("Attention:")
When I get invalid data My summary get 2 times the error as it:
Attention:
Incorrect MyField
Incorrect MyField
Incorrect Another
Incorrect Another
I don't want to rewrite the validation form, here is a lot of views (about 130). I think the problem is in some place in subsonic, but I can't get where :S, Please help me :)
Best regards and thanks in advance.
no way to catch this error :(
Which version of SubSonic are you using? IIRC, Save() in v2.0.3 could call the validation method twice.
Related
I have a lot of controllers in an application.
Controllers called from UI with JS/ajax.
Almost all of them use similar "template". Please see the code sample.
Check income model for null.
Check model is valid.
Try catch with action.
Difference only in error messages, names and which injected helper used.
Is it possible to reduce repeat code?
Some kind of DRY?
How to achieve this? Template method, delegates, use MVC specific things?
[HttpPost]
public async Task<IActionResult> TestMethod([FromBody] TestModel model)
{
if (null == model)
{
return StatusCode((int)HttpStatusCode.BadRequest, "Empty model provided");
}
if (false == ModelState.IsValid)
{
var message = "Not all parameters provided correctly.";
_logger.WriteWithCallerAndMethodName(LogLevel.Debug, nameof(TestController), nameof(TestMethod), message);
return StatusCode((int)HttpStatusCode.BadRequest, message);
}
try
{
var result = await _testHelper.CreateDataAsync(model);
return Ok(result);
// return PartialView("_TestPart", result);
}
catch (Exception ex)
{
var message = $"Can't retrieve data. Error: ({ex.Message})";
_logger.WriteWithCallerAndMethodName(ex, nameof(TestController), nameof(TestMethod), message);
return StatusCode((int)HttpStatusCode.InternalServerError, message);
}
}
In my MVC3 application, I have a "queries" class specific to each controller that performs conversions between domain entities and converts them to view models. I do this to keep my controllers clean and it's easier to unit test the controllers and queries seperately.
There are cases, though, when the query method needs to pass non-exceptional error messages to the view (e.g. the entity was not found). However, since my controller is only receiving a ViewModel from the query method and not any type of return code, the only two options that I have found to pass this error are as follows:
Throw an Exception from the query method and use a Try/Catch block to catch the exception in the controller.
Add a property to the View Model called "ErrorMessage" which is populated by the query method that the view uses to perform logic of what needs displayed.
Because these aren't exceptional cases, and I know I shouldn't use Try/Catch to control program flow, I have choosen to use the second method. Though this works for now, it feels "dirty" to me for the following reasons:
The controller has to receive a whole View Model when an error occurs just to get the ErrorMessage property.
The view has to have hard-coded logic and two sections to display either the error or the normal content
Though I could put the if (Model.ErrorMessage != null) logic in my controller to determine which view to pass, it's still not feeling like a "clean" solution.
Are there any design patterns that I could use that could help me refactor this code and make it cleaner?
Example View Model:
public class ApplicationViewModel
{
public string ErrorMessage { get; set; }
public int Id { get; set; }
public string Name { get; set; }
// Other properties here...
}
Example Controller Method:
public ActionResult Retrieve(Guid guid)
{
return View("Application", _applicationQueries.GetApplicationViewModel(guid));
}
Example ApplicationQueries Method:
public ApplicationViewModel GetApplicationViewModel(Guid guid)
{
var applicationViewModel = new applicationViewModel();
if (!_applicationServices.Exists(guid))
{
applicationViewModel.ErrorMessage = "The requested application does not exist.";
return applicationViewModel;
}
// More code here that checks things which might set the ErrorMessage property...
var application = _applicationServices.GetApplicationByGuid((Guid)guid);
Mapper.Map(grantApplication, grantApplicationViewModel);
return grantApplicationViewModel;
}
Snippit from Application.cshtml View for Error Handling:
#model MyApp.Web.Areas.Application.Models.ApplicationViewModel
if (Model.ErrorMessage != null)
{
<div>#Model.ErrorMessage</div>
}
else
{
<!-- Display "normal" content here //>
}
You could pass the ModelState instance to your queries layer and it will take care to add the error:
public ApplicationViewModel GetApplicationViewModel(Guid guid, ModelStateDictionary modelState)
{
var applicationViewModel = new applicationViewModel();
if (!_applicationServices.Exists(guid))
{
modelState.AddModelError("", "The requested application does not exist.");
return applicationViewModel;
}
// More code here that checks things which might set the ErrorMessage property...
var application = _applicationServices.GetApplicationByGuid((Guid)guid);
Mapper.Map(grantApplication, grantApplicationViewModel);
return grantApplicationViewModel;
}
and in your view:
#model MyApp.Web.Areas.Application.Models.ApplicationViewModel
#Html.ValidationSummary()
#if (ViewData.ModelState.IsValid)
{
<!-- Display "normal" content here //>
}
So here's the deal, i want to be able to export any Enumerable of items to excel:
Here's an ActionMethod in some Area of my app that constructs an "ExportToExcel" model, then Redirects it to an Action Method in another controller and another are which does all the formatting-to-excel work:
public ActionResult ExportCustomListToExcel()
{
var exportModel = new ExportToExcelModel();
//Here I fill up the model with a dataTable / other file info like
//exportModel.Items = blah blah..
return RedirectToAction("ExportToExcel", "Shared", new { model = exportModel, testString = "test", area = "Shared" });
}
And here's my Shared ExportToExcel ActionMethod:
public ActionResult ExportToExcel(ExportToExcelModel model, string testString)
{
//PROBLEM IS RIGHT HERE!
// where testString == "test"
// but model == null :(
//Ommited unrelated code
}
My ExportToExcel actionMethod gets hit, but somewhere along the way my ExportToExcelModel gets lost :(
Note: It succeeds on passing strings like "testString" so is there somwthing wrong with my model?
Just in case, the ExportToExcelModel is:
public class ExportToExcelModel
{
public ExportToExcelModel() {}
public ExportToExcelModel(string fileName, ItemType itemType, IEnumerable<ExportableToExcelItem> items)
{
this.FileName = fileName;
this.ItemType = ItemType;
this.Items = items;
}
public string FileName { get; set; }
public ItemType ItemType { get; set; }
public IEnumerable<ExportableToExcelItem> Items { get; set; }
}
Thanks in advance!
First time i've ever needed to actually ask a question here since every other question i've ever had i've found already answered here :)
EDIT: Posting FormCollection results:
http://imageshack.us/photo/my-images/861/sinttulonsa.png
Sorry, newbies cant post pics :(
The reason is that a RedirectToAction result will launch a GET request and your parameters will have to be passed along through the querystring. Obviously there is a limit to the amount of characters a url can consist of.
Seems to me that you should do the conversion to Excel in a class instead of behind another Action.
So CustomExportAction1 and CustomExportAction2 both call
return File(ExcelExporter.ExportExcel(dataToExport));
or something similar.
try to switch your ExportToExcel signature to
public ActionResult ExportToExcel(FormCollection data)
{
var model = new ExportToExcelModel();
try
{
UpdateModel(model, data)
}
catch(UpdateModelException ex)
{
}
}
look at what's in the FormCollection (that might help), and also see if UpdateModel is throwing an exception, because this is what is happening behind the seen when you make your action method take in a model instead of a FormCollection.
Hope that help you track it down
UPDATE:
You might have to do it using TempData, read this, supposedly you can't do this out of the box with ASP.NET MVC!!
I have a very big problem and can't seem to find anybody else on the internet that has my problem. I sure hope StackOverflow can help me...
I am writing an ASP.NET MVC application and I'm using the Repository concept with Linq To Sql as my data store. Everything is working great in regards to selecting rows from views. And trapping very basic business rule constraints. However, I'm faced with a problem in my stored procedure mappings for deletes, inserts, and updates. Let me explain:
Our DBA has put a lot of work into putting the business logic into all of our stored procedures so that I don't have to worry about it on my end. Sure, I do basic validation, but he manages data integrity and conflicting date constraints, etc... The problem that I'm faced with is that all of the stored procedures (and I mean all) have 5 additional parameters (6 for inserts) that provide information back to me. The idea is that when something breaks, I can prompt the user with the appropriate information from our database.
For example:
sp_AddCategory(
#userID INT,
#categoryName NVARCHAR(100),
#isActive BIT,
#errNumber INT OUTPUT,
#errMessage NVARCHAR(1000) OUTPUT,
#errDetailLogID INT OUTPUT,
#sqlErrNumber INT OUTPUT,
#sqlErrMessage NVARCHAR(1000) OUTPUT,
#newRowID INT OUTPUT)
From the above stored procedure, the first 3 parameters are the only parameters that are used to "Create" the Category record. The remaining parameters are simply used to tell me what happened inside the method. If a business rule is broken inside the stored procedure, he does NOT use the SQL 'RAISEERROR' keyword when business rules are broken. Instead, he provides information about the error back to me using the OUTPUT parameters. He does this for every single stored procedure in our database even the Updates and Deletes. All of the 'Get' calls are done using custom views. They have all been tested and the idea was to make my job easier since I don't have to add the business logic to trap all of the various scenarios to ensure data quality.
As I said, I'm using Linq To Sql, and I'm now faced with a problem. The problem is that my "Category" model object simply has 4 properties on it: CategoryID, CategoryName, UserId, and IsActive. When I opened up the designer to started mapping my properties for the insert, I realized that there is really no (easy) way for me to account for the additional parameters unless I add them to my Model object.
Theoretically what I would LIKE to do is this:
// note: Repository Methods
public void AddCategory(Category category)
{
_dbContext.Categories.InsertOnSubmit(category);
}
public void Save()
{
_dbContext.SubmitChanges();
}
And then from my CategoryController class I would simply do the following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
var category = new Category();
try
{
UpdateModel(category); // simple validation here...
_repository.AddCategory(category);
_repository.Save(); // should get error here!!
return RedirectToAction("Index");
}
catch
{
// manage friendly messages here somehow... (??)
// ...
return View(category);
}
}
What is the best way to manage this using Linq to Sql? I (personally) don't feel that it makes sense to have all of these additional properties added to each model object... For example, the 'Get' should NEVER have errors and I don't want my repository methods to return one type of object for Get calls, but accept another type of object for CUD calls.
Update: My Solution! (Dec. 1, 2009)
Here is what I did to fix my problem. I got rid of my 'Save()' method on all of my repositories. Instead, I added an 'Update()' method to each repository and actually commit the data to the database on each CUD (ie. Create / Update / Delete) call.
I knew that each stored procedure had the same parameters, so I created a class to hold them:
public class MySprocArgs
{
private readonly string _methodName;
public int? Number;
public string Message;
public int? ErrorLogId;
public int? SqlErrorNumber;
public string SqlErrorMessage;
public int? NewRowId;
public MySprocArgs(string methodName)
{
if (string.IsNullOrEmpty(methodName))
throw new ArgumentNullException("methodName");
_methodName = methodName;
}
public string MethodName
{
get { return _methodName; }
}
}
I also created a MySprocException that accepts the MySprocArgs in it's constructor:
public class MySprocException : ApplicationException
{
private readonly MySprocArgs _args;
public MySprocException(MySprocArgs args) : base(args.Message)
{
_args = args;
}
public int? ErrorNumber
{
get { return _args.Number; }
}
public string ErrorMessage
{
get { return _args.Message; }
}
public int? ErrorLogId
{
get { return _args.ErrorLogId; }
}
public int? SqlErrorNumber
{
get { return _args.SqlErrorNumber; }
}
public string SqlErrorMessage
{
get { return _args.SqlErrorMessage; }
}
}
Now here is where it all comes together... Using the example that I started with in my initial inquiry, here is what the 'AddCategory()' method might look like:
public void AddCategory(Category category)
{
var args = new MySprocArgs("AddCategory");
var result = _dbContext.AddWidgetSproc(
category.CreatedByUserId,
category.Name,
category.IsActive,
ref args.Number, // <-- Notice use of 'args'
ref args.Message,
ref args.ErrorLogId,
ref args.SqlErrorNumber,
ref args.SqlErrorMessage,
ref args.NewRowId);
if (result == -1)
throw new MySprocException(args);
}
Now from my controller, I simply do the following:
[HandleError(ExceptionType = typeof(MySprocException), View = "SprocError")]
public class MyController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Category category)
{
if (!ModelState.IsValid)
{
// manage friendly messages
return View(category);
}
_repository.AddCategory(category);
return RedirectToAction("Index");
}
}
The trick to managing the new MySprocException is to simply trap it using the HandleError attribute and redirect the user to a page that understands the MySprocException.
I hope this helps somebody. :)
I don't believe you can add the output parameters to any of your LINQ classes because the parameters do not persist in any table in your database.
But you can handle output parameters in LINQ in the following way.
Add the stored procedure(s) you whish to call to your .dbml using the designer.
Call your stored procedure in your code
using (YourDataContext context = new YourDataContext())
{
Nullable<int> errNumber = null;
String errMessage = null;
Nullable<int> errDetailLogID = null;
Nullable<int> sqlErrNumber = null;
String sqlErrMessage = null;
Nullable<int> newRowID = null;
Nullable<int> userID = 23;
Nullable<bool> isActive=true;
context.YourAddStoredProcedure(userID, "New Category", isActive, ref errNumber, ref errMessage, ref errDetailLogID, ref sqlErrNumber, ref sqlErrMessage, ref newRowID);
}
I haven' tried it yet, but you can look at this article, where he talks about stored procedures that return output parameters.
http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx
Basically drag the stored procedure into your LINQ to SQL designer then it should do the work for you.
The dbContext.SubmitChanges(); will work only for ENTITY FRAMEWORK.I suggest Save,Update and delete will work by using a Single Stored procedure or using 3 different procedure.
I'm passing json back up from my view to my controller actions to perform operations. To convert the json being sent in, to a POCO I'm using this Action Filter:
public class ObjectFilter : ActionFilterAttribute {
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
IList<ErrorInfo> errors = new List<ErrorInfo>();
try {
object o = new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters["postdata"] = o;
}
catch (SerializationException ex) {
errors.Add(new ErrorInfo(null, ex.Message));
}
finally {
filterContext.ActionParameters["errors"] = errors.AsEnumerable();
}
}
It's using the DataContractJsonSerializer to map the JSON, over to my object. My Action is then decorated like so:
[ObjectFilter(RootType = typeof(MyObject))]
public JsonResult updateproduct(MyObject postdata, IEnumerable<ErrorInfo> errors) {
// check if errors has any in the collection!
}
So to surmise, what is going on here, if there is a problem serializing the JSON to the type of object (if a string cannot be parsed as a decimal type or similar for eg), it adds the error to a collection and then passes that error up to the view. It can then check if this collection has an errors and report back to the client.
The issue is that I cannot seem to find out which field has caused the problem. Ideally I'd like to pass back to the view and say "THIS FIELD" had a problem. The SerializationException class does not seem to offer this sort of flexibility.
How would the collective SO hivemind consider tackling this problem?
I would just do an ajax form post. It's much easier.
http://plugins.jquery.com/project/form
http://malsup.com/jquery/form/
How about this: Json.Net
It reads a JSON string and then Deserialises it to the given POCO object.
string jsonResult = GetJsonStringFromSomeService();
MyPocoObject myobject = JsonConvert.DeserializeObject<MyPocoObject>(jsonResult);
Console.Write("Damn that is easy");
But for the determing where errors occur, I am not too sure.