Category Archives: Asp.Net MVC

jqGrid + Linq + Asp.Net MVC example

For those who want get working these tools/frameworks and achieve a grid like this:

jqGridMVCExample

Okey, if you like that, this is the stuff used to get it work:

Download the code example here.

The application was based on the well known example from haacked.com

Asp.net MVC: Testing a custom Authorize filters

Asp.net MVC let you intercept the actions via a feature they call: Filters. Filters are just attributes that you decorate into actions and them allow to you make an stop before or after the action-methods are executed (also are filters to intercept code before/after the result is executed, errors are thrown, etc). There are a few kind of Filter attributes, in the picture bellow into the blue square you’ve what filters came supported out-of-the-box.

Today we are going to talk about the AuthorizeAttribute and how to extend and test it.

AuthorizeAttribute (from the Msdn):

Represents an attribute that is used to restrict access by callers to an action method.

This filter is the first to be called when the Controller Action Invoker try to run Action methods. You can set into the attribute which are the Users or Roles can execute an Action, if the User/Role doesn?t fulfill with what was established into the Action an Unauthorized Result is raised. Remember that exactly after the filter execution ended in a ActionResult, that result is executed.

Now, let?s go to the hypothetical scenario that you need a custom authorization schema, that you need more than User/Role, or you just need neither of both, because your model is based on a Security Level. So you don?t care about who is the guy? / or what role it has?, you just need the security level it has.

With this scenario you can write a custom Authorize attribute:

In this CustomAuthorize attribute, we are doing first the well known authorization (which is, executing the code as is in the class base). When that authorization part passed, we go through our custom authorization part: we get the user from the Database (or whatever other source) and we check the security level. If it?s allowed to execute the action-method we end without setting the result. If it?s not, we set a HttpUnauthorizedResult. In the browser you will be redirected to the login page if you?re not allowed to execute that code.

Now the problem is when you need to test the authorization. Actually you can do it with some mock and overriding some code.

Another thing you?ve to know is that the object in charge of execute the actions is the ControllerActionInvoker. Then to invoke and action into your tests and see the result when the filters are invoked, we need to customize some, and override the method in charge of execute the result (the ActionResult), which is InvokeActionResult. Where is how should looks our method override:

Assert is a class from a Unit Testing framework, in this case in the example is using the Unit Testing framework that came with Visual Studio because every user can run the tests without have ie: Resharper installed. This Assert is expecting that the Result from the filter/action execution is the same with the TResult (is a generic parameter declared into the class). So with this class, we can make an easy test to see if the result is authorized or unauthorized.

Our test for authorized access, should be looking like this

First we are creating a new Controller, we mock stuff for authentication, and then using our custom action invoker to try to invoke the action using InvokeAction method (passing the Context and the Action name to be executed).

We are using some extensions and helpers methods, i.e.: SetFakeAuthenticatedContext is included into the example and there you?ll see which elements you need to mock when use Authorize filter-attributes.

To understand what happened in this first test method:

  1. Controller creation
  2. Mock authentication stuff using our user named:?pepe?.
  3. Using the custom invoker we launch the action ?PermisiveAction?.
  4. The CustomAuthorized filter is raised, it pass the authorization.
  5. The action is executed and return a ViewResult (doing return View() into the code).
  6. The Assertion is made, everything ok and the test pass.

And now let?s see this another test

The difference with the previous one is in the step 4, 5 and 6. The action is not executed because the filter raise an HttpUnauthorizedResult. Download the example to understand better how to manage the testing of Authorization on Actions.

Download code example

NHibernate Validator Quickstart

The NHibernate Validator Team had prepared examples to you be able to use this validation framework in a easy way. With four examples we are covering the following topics:

1) Winforms

In this example you will how you can easily integrate NHibernate Validator and some helper clases with System.Windows.Forms.

2) NHibernate Integration

Trying to integrate NHibernate Validator with NHibernate? Not a problem. In this example you will how really get these 2 great frameworks working together. NHibernate Validator let you intercept Saves and Updates from NHibernate validating your entities before these changes take place. Note you have to create a database based on the configured connection string.

3) Asp.Net MVC

Asp.Net MVC has a cool way to add validation errors from model and display them all into the View. This example cover the easy integration between these frameworks. Note, you need Asp.Net MVC installed into your machine.Download Asp.net MVC

4) Entity Validator

Sometimes you need to validate a property which depends of another(s) property(ies). The most common example is when you have to validate a range of dates. This example cover this funcionality and show to us how to configurate it using attributes, xml and fluent.

Download it here

NHibernate Validator and Asp.Net MVC

 Download the example here.

Asp.Net MVC has a cool way to add validation errors from the model and display them all into the View. It?s actually using the ModelState. As you may know NHibernate Validator (NHV) is a framework to validate entities, so what about if we let the validation to the framework that can manage it? So the integration of NHV to Asp.Net MVC is easy. I created a new Asp.Net MVC project and added some files to my solution to make they look like this:

First I added the libraries needed to NHV (this libraries we need in case to use NHibernate too, otherwise you don?t need Linfu stuff to get proxies working). The libraries are:

Once the libraries are referenced, NHV need to be initialized, actually in this example that initialization will consist in a Validator Engine provider, capable to be accessed from everywhere into our web-application. A good point do this, is in the Global.asax. The next method InitializeValidator it?s called from the Application_Start.

Then I created a new View Manage.aspx, actually the view is a copy, with modifications, of Register.aspx View. Such View should looks like this one. As you may see, seems like there are some messages of validation, means, a validation that didn?t pass.  Now let?s see the code to explore the minimal code to introduce NHibernate Validator as a Framework to Validate our MVC application.

First of all, our entity Customer, which reflex the view with a Name and a Email properties, should looks like this with the NHV attributes. Remember that NHV can be configured using Attributes (default), Xml or Fluent-Interfaces, and accept mix of configurations too.

Second, we need the integration point between NHibernate Validator and Asp.Net MVC, and that point consist just in a little piece of code that make the validation and modifies the current state of the model. We need just a few lines:

The picture shows an extension method which first of all, get a new ValidatorEngine instance, which is a singleton in whole web application. Actually, to use a ValidatorEngine we need just one instance, because NHV make a lot of useful caching and it configure itself in the way we are using it. Then we validate the entity and get all the InvalidValues of the object. If the entity is in invalid state (break one rule defined), NHV we well generate a InvalidValue array with all errors we should show to the user. Iterate through all the items and we add them all to the ModelState. Once we add one model error, the model is no longer valid.

Once we have our extension, let?s use it.

Validate Method is the extension we made before, and that method is going to modify the ModelState if it?s needed.

And that?s all folks, hope this helps.