“Length cannot be less than zero” error when running MVC application

D

Dylan Parry

Hi,

I’ve been tearing my hair out all afternoon on this one, and I’m
probably missing something really simple, but figured I’d ask some
fresher eyes!

I’ve got an MVC application, and one of the pages is supposed to list
some albums that are detailed in a database. I’ve been getting the same
error all day, so I changed the code slightly so that it would just take
the first album in the database and return its title to the browser.

The code for the action method etc is:

--- start ---
private IAlbumsRepository albumsRepository;
public AlbumsController(IAlbumsRepository albumsRepository)
{
this.artistsRepository = artistsRepository;
this.albumsRepository = albumsRepository;
}

public ActionResult Details(string name, string title)
{
return Content(albumsRepository.Albums.First().Title);
}
--- end ---

I’ve used some IoC magic to supply the correct implementation of
“IAlbumsRepository”, which is set up as:

--- start ---
public class SqlAlbumsRepository : IAlbumsRepository
{
private Table<Album> albumsTable;
public SqlAlbumsRepository(string connectionString)
{
albumsTable = (new DataContext(connectionString)).GetTable<Album>();
}

public IQueryable<Album> Albums
{
get { return albumsTable; }
}
}
--- end ---

More IoC stuff in the above supplies the correct “connectionString”. In
case it’s of any help, it’s Castle.Windsor that I’ve used for the IoC stuff.

The “Album” class is a simple class dotted with some attribute tags to
map the various properties to column in the database.

I based the code for all the above on another set of action methods,
repositories and classes that I wrote for “artists”, and those ones work
exactly as expected.

When I run the new stuff however, I get the following error:

---
Server Error in '/' Application.

Length cannot be less than zero.
Parameter name: length

Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Length cannot be
less than zero.
Parameter name: length

Source Error:

Line 36: return Content(albumsRepository.Albums.First().Title);
Line 37: }
Line 38:

Source File: D:\Documents\Visual Studio
2008\Projects\ElectricFreedom\WebUI\Controllers\AlbumsController.cs
Line: 36

Stack Trace:


[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32
length, Boolean fAlwaysCopy) +7495287
System.Data.Linq.SqlClient.ProviderBase.Parse(String stype) +275
System.Data.Linq.SqlClient.SqlFactory.Default(MetaDataMember member) +52

System.Data.Linq.SqlClient.Translator.BuildProjectionInternal(SqlExpression
item, MetaType rowType, IEnumerable`1 members, Boolean allowDeferred,
SqlLink link, Expression source) +835
System.Data.Linq.SqlClient.Translator.BuildProjection(SqlExpression
item, MetaType rowType, Boolean allowDeferred, SqlLink link, Expression
source) +108
System.Data.Linq.SqlClient.Translator.BuildDefaultQuery(MetaType
rowType, Boolean allowDeferred, SqlLink link, Expression source) +154

System.Data.Linq.SqlClient.QueryConverter.TranslateConstantTable(ITable
table, SqlLink link) +109
System.Data.Linq.SqlClient.QueryConverter.CoerceToSequence(SqlNode
node) +96
System.Data.Linq.SqlClient.QueryConverter.VisitFirst(Expression
sequence, LambdaExpression lambda, Boolean isFirst) +30

System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression
mc) +3477

System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression
mc) +74
System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression
node) +1003
System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression
node) +79
System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query,
SqlNodeAnnotations annotations) +114

System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression
query) +132

System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute(Expression
expression) +49
System.Linq.Queryable.First(IQueryable`1 source) +269
WebUI.Controllers.AlbumsController.Details(String name, String
title) in D:\Documents\Visual Studio
2008\Projects\ElectricFreedom\WebUI\Controllers\AlbumsController.cs:36
lambda_method(ExecutionScope , ControllerBase , Object[] ) +136
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary`2 parameters) +178

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters) +24

System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +52

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func`1 continuation) +254

System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +19

System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor,
IDictionary`2 parameters) +192

System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +314
System.Web.Mvc.Controller.ExecuteCore() +105
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39

System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +7
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21

System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult
_) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +59
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +44

System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +7

System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8679150
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously) +155
--- End ---

At first I tried running SQL Server Profiler to find out what was
getting returned, but I soon realised that it’s not even getting as far
as running a query as nothing shows up at all in the profiler window.

I’ve been puzzling on this one all afternoon and I’m baffled. As I said,
I’m probably missing something really obvious, but at this point my eyes
are too tired to see it!

Any ideas?
 
D

Dylan Parry

You have a negative number for your length parameter. I suggest that
you add some code to show you what the value of that parameter
actually is.

Yeah. The problem I’ve got here is that I don’t actually know where the
length parameter is coming from. It’s something that seems to be
calculated automatically by LINQ. I’m not entirely sure what it’s
actually the length of!!
This is the line in your source where the runtime noticed the error.
You may want to consider splitting this line into more than one
statement so as to help localise the error:

// return Content(albumsRepository.Albums.First().Title);
temp1 = albumsRepository.Albums.First();
temp2 = temp1.Title;
temp3 = Content(temp2);
return temp3;

That will allow you to check the value of each of the temp# variables
separately and help localise the problem.

Cheers for that. I separated all the lines out, and it fails as soon as
“First()†is called. This happens both when I try it out on the live
database and when I try it on a faked repository that has a pre-defined
array of albums.
 
D

Dylan Parry

You need to see precisely what, if anything, is in
albumsRepository.Albums

I have two thoughts, first if it is empty then all sorts of nasties
can happen. Second if it has a *lot* of entries then a signed number
might wrap round from positive to negative.

I eventually figured it out a couple of hours ago. For some reason the
error was being caused by some of the LINQ mapping attributes
([Column(…) etc) in the Album class.

I deleted everything apart from the most basic attributes (ie. I left
the primary key definition, and the columns) and it suddenly started
working as expected.

It’s truly bizarre to me as the errors returned bore no resemblance to
the cause of the problem, and it was pure luck that I decided so strip
back the Album class to its bare bones, which then solved the issue.

Thanks for your help though, you got me looking in the right place (ie.
the class causing the problem) :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top