MVC application SESSION for some users null - asp.net-mvc

My problem is with a system i developed for school. We are experiencing some issues for some users. this is the error:
[NullReferenceException: Object reference not set to an instance of an object.]
_360Feedback.Controllers.SurveyController.Answers() +170
lambda_method(Closure , ControllerBase , Object[] ) +78
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +273
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +38
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +119
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +240
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
For some reason the student id is not retained by the session object. I cannot regenerate the error so it is very hard for me to find the reason what is causing this.
Setting the session to cookieless seemed to cause less errors for users, but still generated the error for some users.
I can see that for about 90% of the users everything is working fine. I will post the controller code where this session id is used. I hope you guys can help me.
public ActionResult Start(string x)
{
string decryptedstudentIDString = EncryptionHelper.Decrypt(x);
int studentID = Convert.ToInt32(decryptedstudentIDString);
Student student = repo.FindStudentWithID(studentID);
Session["StudentName"] = student.Name;
Session["StudentID"] = student.StudentID;
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
return View(student);
}
public ActionResult Answers()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
List<Student> remainingStudentInGroup = repo.GetRemainingStudentIDsInGroup(student.StudentID);
student.Answers.Add(new AnswerSet() { AssociatedStudentID = student.StudentID, AssociatedStudentName = student.Name });
foreach (var studentInGroup in remainingStudentInGroup)
{
student.Answers.Add(new AnswerSet() { AssociatedStudentID = studentInGroup.StudentID, AssociatedStudentName = repo.FindStudentWithID(studentInGroup.StudentID).Name });
}
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
Session["StudentID"] = student.StudentID;
Session["GroupSize"] = group.Students.Count;
return View(student);
}
[HttpPost]
public ActionResult Answers(Student student)
{
int s = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"])).StudentID;
foreach (var answerSet in student.Answers)
{
repo.AddAnswerSetToStudent(answerSet, s);
}
return RedirectToAction("Completed");
}
public ActionResult Completed()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == false)
{
repo.SetBooleanForCompletedAnswerToTrue(student.StudentID);
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
ExcelHelper.FillExcelWithAnswersForStudent(group.ExcelFilePath, student);
ExcelHelper.CheckIfAllStudentAnswered(group);
}
return View();
}
Error occurs when users submit form, StudentID is null when they post there answers.

Related

ConnectionString property has not been initialized IIS

Having some issues when I deploy my application to IIS. This is only happening on two pages and the rest of my site works just fine when hitting the database.
public static List<Parent> GetParentsWithAssignedStudentsByISDId()
{
SqlConnection sqlConn = null;
SqlDataReader sqlDataReader = null;
string sConnString = ConfigurationManager.AppSettings["SMARTDBConn"];
var parents = new List<Parent>();
try
{
sqlConn = new SqlConnection(sConnString);
sqlConn.Open();
string commandText = String.Format("SELECT * FROM dbo.ParentFullInfo WHERE ISDId = {0}", Utilities.getISDId());
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConn);
sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
var parent = new Parent() { Students = new List<Student>() };
parent.Id = Convert.ToInt32(sqlDataReader["ParentId"]);
parent.ParentName = sqlDataReader["ParentName"].ToString();
parent.EmailAddress = sqlDataReader["EmailAddress"].ToString();
parent.Address = sqlDataReader["Address"].ToString();
parent.City = sqlDataReader["City"].ToString();
parent.State = sqlDataReader["State"].ToString();
parent.ZipCode = sqlDataReader["ZipCode"].ToString();
parent.WorkNumber = sqlDataReader["WorkNumber"] == DBNull.Value ? string.Empty : sqlDataReader["WorkNumber"].ToString();
parent.PrimaryCellNumber = sqlDataReader["PrimaryCellNumber"] == DBNull.Value ? string.Empty : sqlDataReader["PrimaryCellNumber"].ToString();
parent.HomeNumber = sqlDataReader["HomeNumber"] == DBNull.Value ? string.Empty : sqlDataReader["HomeNumber"].ToString();
parent.Password = sqlDataReader["Password"].ToString();
var student = StudentFactory.GetStudentByStudentId(Convert.ToInt32(sqlDataReader["StudentId"]));
if (!parents.Exists(p => p.Id == parent.Id))
{
parent.Students.Add(student);
parents.Add(parent);
}
else
{
var par = parents.FirstOrDefault(p => p.Id == parent.Id);
if (par != null)
par.Students.Add(student);
}
}
}
finally
{
if (sqlDataReader != null) sqlDataReader.Close();
if (sqlConn != null) sqlConn.Close();
}
return parents;
}
my Web.config does have the proper key
<add key="SMARTDBConn" value="server=ConnStringHere" />
The error
[InvalidOperationException: The ConnectionString property has not been initialized.]
System.Data.SqlClient.SqlConnection.PermissionDemand() +6616256
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6610951
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
SMART_Library.Factories.StudentFactory.GetStudentByStudentId(Int32 studentId) +138
SMART_Library.Factories.ParentFactory.GetParentsWithAssignedStudentsByISDId() +1378
SMARTSupport.Controllers.ParentController.Search(String SearchKey) +48
lambda_method(Closure , ControllerBase , Object[] ) +127
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +270
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +120
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +240
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +74
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

"Sequence contains no elements" when using .Any()

This seems like a straightforward question. I am beginning to suspect a bug in razor.
if (Model.athleteImages .Any()){
//some code
}
I have replaced the above with the following:
if (Model.athleteImages.Count > 0)
{
var i = 0;
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
while (i + 1 < Model.athleteImages.Count())
{
i++;
<li data-target="#carousel-example-generic" data-slide-to="#i"></li>
}
}
This always throws "Sequence contains no elements" for collections with no elements e.g. Count() = 0.
Any() is supposed to test if a Sequence contains elements. That is its entire purpose.
I have also tried
if (Model.athleteImages.FirstOrDefault().[fieldName] != null){
//some code
}
Same result.
here is some relevant code from the controller for those wondering what the Images collection is
var adImages = from i in db.athleteImages
where thisAd.albumId == i.albumId
where i.deleted == false
select i;
viewModel.athleteImages = athleteImages.ToList();
Here is the View Model Class
public class ListingViewModel
{
public site site { get; set; }
public userAd userAd { get; set; }
public List<athleteImage> athleteImages { get; set; }
public string categoryName { get; set; }
public int categoryId { get; set; }
public string subcategoryName { get; set; }
public int subcategoryId { get; set; }
}
Stack Trace
[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.First(IEnumerable`1 source) +269
ASP._Page_Views_userAds_Listing_cshtml.Execute() in c:\Users\Bill\Documents\Visual Studio 2013\Projects\CuriousMarketplaces\CuriousMarketplaces\Views\userAds\Listing.cshtml:32
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
If what you really care about is whether or not there are any images in the collection, something like this might make more sense:
if (Model.Images.Count > 0) {
}
Any() will throw an exception if the source is null, this is documented behavior and how it is supposed to work: http://msdn.microsoft.com/en-us/library/vstudio/bb534972%28v=vs.100%29.aspx
Dave's solution is pretty good but I would add a null check, Count will also throw an exception if the object is null.
if(Model.Images != null && Model.Images.Count > 0) {
}
Dan gave me the hint I needed.
Even though the debugger was indicating that the error was occurring at the closing block of my if block, that was not the case.
In a later block of code in the same view, I have this:
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
To fix the problem, I need to test again. so:
if (Model.athleteImages.Count > 0)
{
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
}
What fries my brain is that the error message indicated a problem at line 32. In reality it was on line 37.

No Handler Registered CQRS-ES

I am creating a cqrs-es test application. I scan command handler against command by following code
public class StructureMapCommandHandlerFactory : ICommandHandlerFactory
{
public ICommandHandler<T> GetHandler<T>() where T : Command
{
var handlers = GetHandlerTypes<T>().ToList();
var cmdHandler = handlers.Select(handler =>
(ICommandHandler<T>)ObjectFactory.GetInstance(handler)).FirstOrDefault();
return cmdHandler;
}
private IEnumerable<Type> GetHandlerTypes<T>() where T : Command
{
var handlers = typeof(ICommandHandler<>).Assembly.GetExportedTypes()
.Where(x => x.GetInterfaces()
.Any(a => a.IsGenericType && a.GetGenericTypeDefinition() == typeof(ICommandHandler<>)))
.Where(h => h.GetInterfaces()
.Any(ii => ii.GetGenericArguments()
.Any(aa => aa == typeof(T)))).ToList();
return handlers;
}
}
I dispatches command as follows:
public class CommandBus:ICommandBus
{
private readonly ICommandHandlerFactory _commandHandlerFactory;
public CommandBus(ICommandHandlerFactory commandHandlerFactory)
{
_commandHandlerFactory = commandHandlerFactory;
}
public void Send<T>(T command) where T : Command
{
var handler = _commandHandlerFactory.GetHandler<T>();
if (handler != null)
{
handler.Execute(command);
}
else
{
throw new UnregisteredDomainCommandException("no handler registered");
}
}
}
When I run the project it throw an exception
"No Handler Registered"
My project location is https://drive.google.com/file/d/0B1rU7HOTfLwea0tVOXdIb2Nib2M/edit?usp=sharing
The Stack-Trace of this exception as follow:
[UnregisteredDomainCommandException: no handler registered]
CQRS.Infrastructure.Messaging.CommandBus.Send(T command) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\CQRS.Infrastructure\Messaging\CommandBus.cs:31
HRMSWeb.Facade.DiaryItemFacade.Delete(Guid id) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\HRMSWeb\Facade\DiaryItemFacade.cs:59
HRMSWeb.Controllers.HomeController.Delete(Guid id) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\HRMSWeb\Controllers\HomeController.cs:29
lambda_method(Closure , ControllerBase , Object[] ) +184
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c_DisplayClass42.b_41() +28
System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c_DisplayClass39.b_33() +57
System.Web.Mvc.Async.<>c_DisplayClass4f.b_49() +223
System.Web.Mvc.Async.<>c_DisplayClass37.b_36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c_DisplayClass8.b_3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The problem is on your ObjectFactory.
I don't know if you use some DI container (I can't see your code), but it can't retrieve your handlers.
You should use some kind of Typed Factory, so you could retrieve more than one commandHandler (as you do in your code).
I send you the link of my training journey into CQRS/ES: it's very similar to what you're doing and there are some articles about the journey.
I Hope it helps.

Problems with deploying MVC 4 app on Windows Server 2008

I have deployed this MVC app on my localhost(on my machine running windows 8) and it runs as expected. The only difference between my installation folder and the one which is on the server, is the connection string. But when I try to deploy it on the server machine(Windows Server 2008) I get this strange error :
[NullReferenceException: Object reference not set to an instance of an object.]
PicknikMVC.ViewModels.ApplicationViewModel..ctor(Application app) in c:\Builds\workspace\Picknik\AppStoreService\target\checkout\AppStoreService\PicknikMVC\ViewModels\Application\ApplicationViewModel.cs:23
PicknikMVC.Controllers.Application.ShowController.Execute(String appid) in c:\Builds\workspace\Picknik\AppStoreService\target\checkout\AppStoreService\PicknikMVC\Controllers\Application\ShowController.cs:59
lambda_method(Closure , ControllerBase , Object[] ) +126
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)+247
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +38
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +119
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +31
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +230
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
The code in the app where this happens is basically instantiating a new object of particular class with some information from the database. Do you see any obvious problem? Could it be a problem with the connection string or it is something else?
AppViewModel:
public class ApplicationViewModel
{
public int App_ID { get; set; }
public string Title { get; set; }
public string Developer { get; set; }
public string DeveloperURL { get; set; }
public bool IsImportant { get; set; }
public IEnumerable<ScreenshotPairViewModel> Screenshots { get; set; }
public ApplicationViewModel(PicknikData.Application app)
{
App_ID = app.App_ID;
Title = app.Title;
Developer = app.Developer;
DeveloperURL = app.DeveloperURL;
if (app.IsImportant.HasValue)
{
IsImportant = app.IsImportant.Value;
}
Screenshots = app.ScreenshotURLs.Select(p => new ScreenshotPairViewModel(p.Screenshot_URL,p.FK_Device)).ToList();
}
}
and the code for the controller:
viewModel.Application = new ApplicationViewModel(app);
It is hard to tell from the info provided, but I'll have a bash at helping.
If the connection string is different, I assume the data might be too.
When you see object not set, it is usually something not instantiated in the code. In this case though, it could be the data. Assuming everything is instantiated somewhere, it is possible there are no ScreenshotURLs? The error message details a lambda error, so I assume the it relates to the select statement.

WebGrid.GetHtml() throws Object reference not set to an instance of an object when the

Description
I can not get the WebGrid sort to work. It keeps throwing NullReferenceException when the view tries to load.
Environment
WebGrid 2.0.0.0, VisualStudio 2012, MVC version 4.0
Details
My controller action does not attempt to do any sorting yet. I tried to simulate the sort by clicking on a column header, the controller's index action executes without any errors. When the view tries to load I get a runtime error NullReferenceException was unhandled by user code
In debug mode I can trace the error back to some code in the WebGrid's GetHtml call that attempts to reference the Rows object 'grid2.Rows' threw an exception of type 'System.NullReferenceException'
I am using a strongly typed collection to fake up some data in the controller, add it to the model and serve the model to the view.
I have tried a number of different variations, but here is the current state of my code:
The controller action
public class HomeController : Controller
{
public ActionResult Index(string sort, string sortdir)
{
LandingPageData myData = new LandingPageData();
myData.UserName = "JoeBagodonuts";
ReplacementReserveMvcDesign.ViewModels.ProjectCounts<ProjectCount> currentWork = new ProjectCounts<ProjectCount>();
//Hacking up some data
for (int i = 0; i < 1000; i++)
{
ProjectCount currentCount = new ProjectCount();
currentCount.ProjectId = "PA-" + i.ToString();
currentCount.DevelopmentName = "Development Name " + i.ToString();
currentCount.OpenCount = i;
currentCount.ActionRequiredCount = i;
currentWork.Add(currentCount);
}
myData.UserProjectCounts = currentWork;
return View(myData.UserProjectCounts);
}
The View
#model IEnumerable<ProjectCount>
#using System.Web.Helpers
#using ReplacementReserveMvcDesign.ViewModels
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
WebGrid grid2 = new WebGrid(Model, canSort:true);
}
#grid2.GetHtml(
columns: grid2.Columns(
grid2.Column(columnName:"ProjectId",
header: "Project ID"),
grid2.Column(columnName:"DevelopmentName",
header:"Development Name"),
grid2.Column(columnName:"OpenCount",
style: "text-align-center",
header: "Open Requests"),
grid2.Column(columnName:"ActionRequiredCount",
header: "Action Required",
style: "text-align-center")
))
Here is the stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , ProjectCount ) +81
System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count) +147
System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count) +37
System.Linq.<GetEnumerator>d__0.MoveNext() +330
System.Linq.<SkipIterator>d__4d`1.MoveNext() +397
System.Linq.<TakeIterator>d__3a`1.MoveNext() +375
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +535
System.Linq.Enumerable.ToList(IEnumerable`1 source) +79
System.Web.Helpers.WebGridDataSource.GetRows(SortInfo sortInfo, Int32 pageIndex) +166
System.Web.Helpers.WebGrid.get_Rows() +118
System.Web.Helpers.<>c__DisplayClass4.<Table>b__3(TextWriter __razor_helper_writer) +1191
System.Web.WebPages.HelperResult.ToString() +102
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, Object content) +16
ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Users\is_rbm\documents\visual studio 2012 \projects\replacementreservemvcdesign\replacementreservemvcdesign\Views\Home\Index.cshtml:14
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +279
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +125
System.Web.WebPages.StartPage.ExecutePageHierarchy() +142
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +180
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +377
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +32
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854204
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838676
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
I am eager to use MVC in this project, but I have to be able to build searchable,sortable and pageable grids quickly and easily.
I changed the controller's index method to return a List of ProjectCount objects rather than a strongly typed collection and everything work now.
Here's the new code for the controller index method.
public ActionResult Index(string sort, string sortdir)
{
List<ProjectCount> items = new List<ProjectCount>();
for (int i = 0; i < 1000000; i++)
{
ProjectCount currentCount = new ProjectCount();
currentCount.ProjectId = "PA-" + i.ToString();
currentCount.DevelopmentName = "Development Name " + i.ToString();
currentCount.OpenCount = i;
currentCount.ActionRequiredCount = i;
items.Add(currentCount);
}
return View(items);
}

Resources