Are attributes on regular methods possible [closed] - c#

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.

Related

When should someone use Remote Attribute vs Custom Attribute [closed]

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.

Where would you place a method that has the same functionality but is inside 2 subclasses and has different parameters? [closed]

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 7 years ago.
Improve this question
I am trying to restructure an application, and right now there are two classes which are subclasses of another class.
Both of these classes have a method. This method essentially does the same thing (get user information) but from different data sources and parses them differently (say one uses the Facebook API and the other a database). They also take in different parameters.
Does it structurally make sense to leave both methods in the subclasses with the same method name? Or is there a cleaner way of organizing the methods within the subclasses?
Even though both methods are logically GetUserInfo, it is also correct that one is logically GetUserInfoFromFB and the other GetUserInfoFromDB.
You could create an abstract GetUserInfo method, but since the methods get different parameters, it could easily get messy. It is easily feasible, however, if the parameters can be logically refactored as properties of the subclass (or properties of logical class to hold them together, that being a property of the subclass).
Edit: The strategy pattern is applicable here, but is what I would consider "messy". Your case as you presented it is small in scale, so the the strategy pattern just might be an overkill.
tl;dr If you do not think your case justifies the strategy design pattern, it is perfectly fine to leave it as it is.
This is a perfect place to apply the strategy pattern.
Rather than having a different GetUserInformationMethod call for each class, create a new class (or a delegate type) that exists just to get user information. Have a UserInformationGetter attribute which is an instance of your user information fetching class/delgate in the base class, and have the base class's GetUserInformation method invoke the delegate/class to get user information.
The challenge of different parameters could be handled in a number of different ways, which depends on the parameters. If the parameters are related to the details of implementation (e.g. database connection strings), and not variant across users then you should tie that information to the UserInformationGetter class.
If the information is dependent on the user, there are a number of strategies. I would suggest you create a type that encapsulates all the information about the user that is used to fetch user data in either case. Then you can pass this object to the methods, rather than parameters that vary accoridng to the method of data access.
This way, you can vary the user information fetching strategy of your base classes independently of anything else which might vary between the classes. Additionally, you can vary the way you get user information at runtime, allowing your program to adapt to changing requirements easily.

Code reusability: how to refactor checks to be more readable and reusable, separating responsabilities? [closed]

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.

Specification Pattern Unit Tests [closed]

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 5 years ago.
Improve this question
We have recently adopted the specification patterns for validating domain objects and now want to introduce unit testing of our domain objects to improve code quality.
One problem I have found is how best to unit test the validate functionality shown in the example below. The specification hits the database so I want to be able to mock it but as it is instantiated in-line I can't do this. I could work off interfaces but this increases the complexity of the code and as we may have a lot of specifications we will ultimately have a lot of interfaces (remember we are introducing unit testing and don't want to give anyone an excuse to shoot it down).
Given this scenario how would we best solve the problem of unit testing the specification pattern in our domain objects?
...
public void Validate()
{
if(DuplicateUsername())
{ throw new ValidationException(); }
}
public bool DuplicateUsername()
{
var spec = new DuplicateUsernameSpecification();
return spec.IsSatisfiedBy(this);
}
A more gentle introduction of Seams into the application could be achieved by making core methods virtual. This means that you would be able to use the Extract and Override technique for unit testing.
In greenfield development I find this technique suboptimal because there are better alternatives available, but it's a good way to retrofit testability to already existing code.
As an example, you write that your Specification hits the database. Within that implementaiton, you could extract that part of the specification to a Factory Method that you can then override in your unit tests.
In general, the book Working Effectively with Legacy Code provides much valuable guidance on how to make code testable.
If you dont want to do constructor injection of a factory, and make the specs mockable... Have you considered TypeMock? It is very powerful for dealing with this sort of thing. You can tell it to mock the next object of type X that is to be created, and it can mock anything, no virtuals etc required.
You could extract getDuplicateUsernameSpecification() into a public method of its own, then subclass and override that for your tests.
If you use IoC then you can resolve the DuplicateUsernameSpecification and in test mockup the last one
Edit: The idea is to replace direct constructor call with factory method. Something like this:
public bool DuplicateUsername()
{
var spec = MyIocContainer.Resolve<DuplicateUsernameSpecification>();
return spec.IsSatisfiedBy(this);
}

What's the best way to implement field validation using ASP.NET MVC? [closed]

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

Categories

Resources