My Software Notes

Useful things I discover

Archive for the ‘ASP.NET MVC’ Category

IValidatableObject for Complex Custom Validation

leave a comment »

Just a note to help me remember the IValidatableObject interface that is used in ASP.NET MVC for adding complex custom validation to a view model.

You can put data annotations on a view model so when the data comes back from a request (e.g., a form post) and the data is being bound to the model, the data annotations can be used to validate that the data coming in is correct.

Example: the property on the view model is a string and you put the StringLengthAttribute on it to specify that the length must be from 5 to 10 characters. If the value in the property is 12 characters then that will be caught and an entry will be added to the ModelState.

But what if your validation is complex? For example, you have property X that is a date that can’t be in the future and can’t be later than the date in property Y, but the date in property X is only required if the item has not been discontinued (a value of false in property Z).

You could write a custom data annotation, but it’s unlikely you’ll ever reuse it, so instead use the IValidatableObject interface.  Implement it on your view model and a Validate() method is added to your model that you can use to run your custom validations.

Rather than reinvent the wheel, here are some useful references on how to do it:




Written by gsdwriter

June 20, 2017 at 11:59 am

ASP.NET Timouts (Sessions and App Pools and Auths, Oh My)

with 4 comments

I just had to extend the timeout for an ASP.NET site and I had to look it up all over again.  I don’t extend timeouts very often but when I do I never remember all the places that I may need to make a change.  Sadly just changing sessionState in the Web.Config doesn’t always cut it.

So here, for my future use and for anyone else with the same problem, are a list of all the timeout possibilities that I know of in ASP.NET web apps.

Session State – In web.config

Session state timeout is 20 mins by default.  To increase it set the timeout attribute on the sessionState element in the web.config.

     <sessionState timeout="60" /> 


ASP.NET Session Timeouts

sessionState Element

App Pool Idle Time-out – In IIS

The Application Pool of your web app has an “Idle Time-out (in minutes)” setting in “Advanced Settings” (IIS7)  The help text says: “Amount of time (in minutes ) a worker process will remain idle before it shuts down.”


ASP.NET Session Timeouts

Configure Idle Time-out Settings for an Application Pool (IIS 7)

Forms Authentication Timeout – In web.config

Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page even if the session is still active.  The setting is in minutes.

     <authentication mode="Forms">
           <forms timeout="50"/>


Answer to question about Session Timeout in ASP.NET

forms Element for authentication

Recycle Worker Process – in IIS

Not really a timeout but it will have that effect.  The default is 29 hours, so you will rarely need to change it.


ASP.NET Session Timeouts

Configuring Recycling Settings for an Application Pool (IIS 7)

Execution Timeout – in web.config and in code

This is the time allowed for a request to execute before it is shut down.  The default is 110 seconds, so it’s plenty long enough for most situations.  If you need to make it longer for your entire site then use web.config and if you need to lengthen it for just a specific request then do it in code.

In Web.Config:

   <httpRuntime executionTimeout="180" />

If compilation debug is true then the timeout is always about a year (really).  This is so your app doesn’t stop handling a request while you are running through the debugger in Visual Studio.


ASP.NET Session Timeouts

httpRuntime Element

In Code:

The HttpServerUtility class has a property called ScriptTimeout that allows you to set the timeout for the current request.  In ASP.NET and ASP.NET MVC you can get at this property via the Server property of your Page or Controller.

Server.ScriptTimeout = 600;  //in seconds


HttpServerUtility.ScriptTimeout Property

Timeout of an ASP.NET page

ASP.NET Session Timeouts

Security Token Handlers – In web.config and code

Here’s another one I just came across (01/20/2014).  This can be used to replace the forms authentication timeout.

In Web.Config

The “lifetime” attribute in the sessionTokenRequirement element can be used to set the timeout. It uses the format “hh:mm:ss”.

      <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,System.IdentityModel, 
      	Version=, Culture=neutral,PublicKeyToken=B77A5C561934E089" />
      <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,System.IdentityModel.Services, 
      	Version=, Culture=neutral,PublicKeyToken=B77A5C561934E089">
        <sessionTokenRequirement lifetime="00:20:00"></sessionTokenRequirement>

In Code

Classes derived from SecurityTokenHandler have a TokenLifetime property that can be set using a TimeSpan.

tokenHandler.TokenLifetime = new TimeSpan(0, 20, 0); //hh, mm, ss



SessionSecurityTokenHandler Class


I think that’s everything.  If not please leave a comment and enlighten me 🙂

If you have any other useful links on the subject please leave those too.

Written by gsdwriter

June 22, 2012 at 10:55 am


MVC 4 Beta Major Gotcha

leave a comment »

After installing MVC 4 Beta, I noticed that Visual Studio 2010 Intellisense had developed a problem in Razor views in MVC 3 projects.  For example ViewBag wasn’t found and neither was Url.

I looked around for solutions and found various suggestions, but none of them worked and then (I’m not sure whether to say “Duh” or not) I found the solution in the release notes: ASP.NET MVC 4 Beta: Known Issues and BREAKING CHANGES.  (See the “Required Updates” section.)

Now I know that ideally I should have looked at the release notes before installing it.  Sure, and ideally I should never drive faster than the speed limit, but this is the real world and the ideal and the actual don’t always coincide.

I really think that the “Known Issues and Breaking Changes” section of the release notes should have their own link (in BIG CAPS) right next to the big green “Install ASP.NET MVC 4 Beta” button on the ASP.NET MVC 4 page, so that idiots like me will pay attention and maybe actually know ahead of time what might break and take the necessary steps.

For the other poor sods who don’t read release notes here are a couple of the searches I can remember I made and hopefully if you search on the same terms you may find this post.

  • MVC 4 Beta breaks Intellisense
  • MVC 3 Razor View Intellisense Not Working

PS: MVC 4 itself is good so far.

Written by gsdwriter

March 5, 2012 at 10:49 am

MVC 4 Beta – Single Page Application Tutorial – Gotcha

with 6 comments

I’m currently trying out the ASP.NET MVC 4 Beta and I thought I’d give the Single Page Application tutorial a shot.

I’ve created several single page apps so far and they’re working well and people are using them successfully, but now that I’ve had some experience I look at them and wish I could rewrite them from scratch.  If you look back at code you wrote six months ago and don’t think that you could do it better now then either you are perfect or you have stopped learning and are fast becoming antiquated.

Anyway, I want to start using frameworks like knockout.js and backbone.js, and the SPA (Single Page Application) template that comes with MVC 4 uses knockout.js – great.

So I followed the instructions, hit F5 to run the web site, typed “Tasks” in the address bar and … aaargh!  An exceptions in the view and a really unhelpful error message.  “System.InvalidOperationException was unhandled by user code” and “Failed to get the MetadataWorkspace for the DbContext type ‘MvcSpaApp1.Models.MvcSpaApp1Context’.”  The inner exception was no better: “System.Data.ProviderIncompatibleException” and “The provider did not return a ProviderManifestToken string.”

Luckily I’ve been reading up on Entity Framework Code First, so I knew what the problem was – I didn’t have SQL Server Express running.  So I started up SQL Server Express and … still didn’t work.  But this time it was because I didn’t have rights to SQL Server because I was using a machine someone else set up and they had mucked up the security.  Anyway, when I finally got it all sorted out the site ran without any problems.


Other than those gotchas the tutorial is good.

Written by gsdwriter

March 2, 2012 at 11:29 am

ASP.NET MVC SelectList Constructor

with 12 comments

I was creating a drop down list in an MVC application and the list was okay, but the selected item was not being selected.

I was using the SelectList object and the constructor that takes four parameters, the last parameter being selectedValue.  The documentation on MSDN is not exactly enlightening.  All it says for the parameter is “The selected value”.  Wow, big help.

This is what I finally figured out.

Here is the constructor:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
  • items is the list of “things” you want to put in the drop down list (“select” HTML tag).
  • dataValueField is the name of the property on your “things” that you want to be put into the “value” attribute of the “option” tag rendered in the HTML.
  • dataTextField is the name of the property on your “things” that you want to be displayed in the drop down list (the text between the “<option>” and “</option>” in the “select”) .
  • selectedValue is the value you want to end up as selected in the drop down list. It has to be the same as what will be put into the “value” attribute of the “option” tag in the rendered HTML.

Example:  I have a class called Thing that has a property “ID” and a property “Description”.  I want something like this:

<option value="1">Description One</option>
<option value="2" selected="selected">Description Two</option>
<option value="3">Description Three</option

I have a List<Thing> that I will use to populate the drop down. I have a Thing that is the selected Thing.

List<Thing> things = GetThings();
Thing selectedThing = GetSelectedThing();
var selectList = new SelectList(things, "ID", "Description", selectedThing.ID);
ViewData["things"] = selectList;

So it works if the fourth constructor parameter is the exact value you want to match.  I’m not sure if it needs to be a string or not, I’ve not had time to check that.

03/11/2013 – I just came across these two excellent articles on using the Html.DropDownList and Html.DropDownListFor helper methods.  These might also shed some light on how to work with SelectList and why you may not even need to:

Drop-down Lists and ASP.NET MVC

DropDownListFor with ASP.NET MVC


Written by gsdwriter

February 17, 2010 at 4:56 pm

Posted in ASP.NET MVC