Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
If I`m not mistaken, Remote Attribute Validate execute on Value Change, so it doesn't require you to press Submit, However Custom Attribute requires that we Write JQuery to call Adaptor
So my Question is why not use Remote Attribute all the time ?
The primary purpose of a RemoteAttribute is to perform validation logic in the controller while staying on the same page. Most often its used when you need to access an external resource (for example to check that a new user is not using an existing user name when registering), but it could also be because the logic is so complex that it is not worth duplicating/maintaining it in a client side script.
Two important things to consider about the RemoteAttribute.
It uses ajax to make a call to a server side method. Initially the
ajax call is made after editing a control in the .blur() event,
but thereafter on every .keyup() event so using a
RemoteAttribute will be a performance hit
It provides only client side validation (which should only ever be
considered a nice bonus) and you still need to then implement server
side validation to prevent a malicious user by-passing the client
side validation
If your writing a custom validation attribute where the validation logic can be performed using javascript, then your attribute should inherit from ValidationAttribute and implement IClientValidatable (and include the necessary scripts to add the client side rules) so that you get both client and server side validation without making unnecessary calls to the server.
Refer The Complete Guide to Validation in ASP.NET MVC 3 - Part 2 for a good article on implementing custom validation attributes.
Related
Basically I don't even know where to register an event handler at the controller instance, because instantiation is handled by the DI container and I'd like to register at the newly created controller instance.
Is this even advisable to do, or is there a better way which fits the architecture of ASP.NET Core?
The scenario is this:
A hidden link is available to some anonymous user until an expiry date.
First use case:
Any anonymous user can manually "close" the link (make it invalid/unavailable) using a Web API call to a controller method.
This method could raise an OnLinkClosed event.
Second use case:
A "chron job" checks the hidden links database table and if one expired it will set the entry to "closed" (instead of a user). It might call a differnt API function (i.e. because now we know who/what closed the link) but the reaction to it is basically the same.
This could raise an OnLinkClosedByChronJob event.
Reacting to OnLinkClosed, OnLinkClosedByChronJob:
The link data in the DB needs to be flagged as closed.
Some data needs to checked and the original creator (who ist known) of the hidden link needs to be informed via e-mail.
(Maybe a SignalR broadcast needs to happen.)
(Maybe some statistics need updating.)
I don't want to hard code all this (and later) functionality in the controller method (to avoid long controller methods would be one concern). Maybe I should do it in a service!? I'm not so sure yet of when to place code in the controller method or into a service. (Except when I need the service functionality in more than one controller, obviously. Any hints/articles covering this topic are appreciated.)
I don't necessarily want to use MediatR or the functional approach (see here: https://www.youtube.com/watch?v=IROSd7uB-tg&t=35m11s) but it may be what I'm looking for.
At best I want to do all/some of the reaction functionality asynchronously or even in parallel.
An event like "this link got closed - anyone interested?" seemed to be a viable idea.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Hi I'd like to put security attributes on regular instance methods. Here is an example:
[EnsureUserIsAdmin] //I want something like this
public IEnumerable<NameItem> GetNameItems(int Id)
{
return _nameDataController.GetNameItems(Id);
}
This method is in my business logic. Any other code that uses this method will have to go through a check to see if the user is an admin. If it is possible to do this how would I unit test it?
Assuming that what you are asking is whether you can arbitrarily restrict access to methods in an automated fashion using an attribute, then if your application's security principal object is a Windows Principal (eg. you are using Active Directory or Windows Authentication), yes you can, using the PrincipalPermission Attribute.
[PrincipalPermission(SecurityAction.Demand, Role = "MyAdminRole")]
public void TestMethod()
{
}
Filter attribute unlike normal Attribute, resides on Controller Actions and are part of the ASP.NET controller execution process and are gathered and executed by the Routing engine.
The solution is not out of the box, and will required fair amount of non trivial complexity.
In case of non-action method you have the option of creating your own controlled environment, which will be limited and a little forced.
I would against it and use normal method preconditions or calling another validation method inside your target method to test for "security" or other validations, but certainly not attributes.
If you still want using attributes, then the following can be a solution.
You will need to make some kind of CustomSecurityManager which will execute the targeted method you want, he will have the responsibilities of:
Finding the target method
Collecting specific custom attributes and running them, throw exception or return false if there are issues.
Run the method if the attributes are valid.
Note: Only the CustomSecurityManager is calling the GetNameItems.
Unit testing can be achieved by Injecting a ICustomSecurityManager which will be mocked to return expected results.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In theory a large 1000+ line of code behind code is "bad practice" what if the majority of the code effects controls on the page?
For example what if there were 30 text boxes to collect user data, but depending upon answers to questions, visibility, validation, etc changed on these text boxes.
Should you then be writting methods in classes for validation that take collections of text boxes and disable validation, or set the visibility? I'm having a hard time wrapping my mind around the design practices of large code files.
I guess I'd like to know the best practice for breaking out large code behind files that still allows for easy control manipulation.
I'd devide the text boxes into groups depending on the contents. Make a User Control for each group (With a dedicated visual container). A user control can take care of validation and some computations, but it is very readable and can event be reused somewhere else if the problem you are solving allows that.
Another option is to use a wizard. This could be more complicated, but if you have the time, you can get nice results.
First of all I do not think 1000+ is not too much for a code behind file at all and I wouldn't consider this bad practice as long as you follow the DRY ( do not repeat yourself ) approach. If you really want to split this up there might be a possibility to have more code behind files for group of controls and do ajax requests to validate parts of the page. You could then evaluate the results from the ajax calls and check if the return message is success and assume that the validation is successfully if all individual ajax calls have a success flag.
For ASP.NET I do most of the logic on the client side with the knockout framework using the visible binding:
http://knockoutjs.com/documentation/visible-binding.html
I use knockout to generate the controls via foreach binding and set the visible binding to an observable inside the obserable array. If the array you pass to the foreach binding is an obserable array you can also add / remove controls via JS.
You could use a validation framework and on validation you can change the observable array adding more questions / removing questions from HTTP post.
Another option would be to do the validation on the server side.
You can check in the post method the values which have been submitted and change the view model adding or removing elements. You then return the view with the modified model.
If required I would use a strongly typed collection to have a reference for the page elements and modify the properties as required.
For WPF I use Observable collections to track property change events which notifies the UI when the collection changes.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Consider the following check. I can find the same identical error check 10 times across my solution.
if (request == null)
throw GetFaultException("Request object is null");
Now consider the next one:
if (model == null)
throw GetFaultException("Request model not well formed");
The only stuff that is changing is the error message and the name of the checked variable.
One part of refactoring had already been done since the GetFaultException is already hiding complexity and separating responsibilities.
I see many possible further refactoring. Like using Monads, AOP, events (?).
I think the really really best solution would be to make the code thinking like in a MVC model.
Thus if (condition) request == null then (it means) A mandatory parameter has not been specified then (it means) An exception is needed with a specific message
The good stuff I see in this approach is that the procedural programming makes the code unspeaking and unaware. Instead if I raise a NullMandatoryParameterEvent it's really clear why I'm checking a variable for being null and what I do if it is null.
The question is: how would you refactor this kind of Check (according to the objective I've defined)? And do you share these objectives?
I assume that your program cannot continue if the validated property is null. Therefore, I'd stick with exceptions - this is exactly the situation that the ArgumentNullException was invented for. You can state the parameter that was null and by that communicate clearly what the caller should fix in order to get the code running. Events are not an alternative to exceptions as the caller might or might not handle them.
In my projects I've also tried to optimize the code layout by putting the validation logic in one place. In smaller projects by creating some helper methods like AssertIsNotNull that takes the parameter and the name as an input so that it can construct and throw an ArgumentNullException.
In my last project, one that is expected to grow heavily, I've created a specific ValidationService and used AOP to put the logic in place. I've also used the attributes located in the System.ComponentModel.DataAnnotations namespace to declare the rules that should be validated in addition to the input parameter being not null. MVC uses the same attributes to validate the models both on the client (through JavaScript) and on the server.
Another approach you might consider is using code contracts. Though you still have to define the preconditions in each method, you can use static code analysis to find spots that violate the contract. You can also configure when the checks are done. For instance, you can run all the checks while in testing and skip certain tests for a production environment for performance reasons. For an overview also see this link.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.
Take a look at the JQuery Validation plugin this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.
Also a sample MVC controller method can be found here which basically uses the JsonResult action type like:
public JsonResult CheckUserName(string username)
{
return Json(CheckValidUsername(username));
}
IMO using xVal with jQuery and DataAnnotationsModelBinder is the best combination.
Sometimes however, there are validation rules which cannot be checked entirely on the client side, so you need to use remote client-side validation.
I figured out way to generically implement remote client-side validation with xVal / jQuery.validate so that
Validation rules remain solely in your ASP.NET MVC model
You write each validation rule just once, and only in easily testable C# code. There is no JavaScript or other client-side counterpart .
There is no need to branch or otherwise modify xVal or jquery.validate
All you have to do for each new remote form validation rule is to derive from the base class shown in this article.
I wrote a blog article on this describing all the details.
My favorite way it perform both client and server validation using model-based attributes. I wrote a short post about this and released the source code as well, that will basically allow you to create a class like this
class User {
[Required]
public string Name{get;set;}
[Email][Required]
public string Email {get;set;}
}
And the appropriate javascript code will be generated to perform client validation as well as server-side validation runner will be validate your submitted form.
Read the post over here