MVC Routing and Custom Error Page Not Found Problem - asp.net-mvc-2

I am using my own controller factory in an MVC 2 app, and this standard code which seems to be going around:
protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
{
...
// Error handling
if (controllerType == null)
{
throw new HttpException(
404, String.Format(
"The controller for path '{0}' could not be found" +
" or it does not implement IController.",
reqContext.HttpContext.Request.Path
)
);
}
...
}
The problem I was having is one others have asked about, where certain resources where being caught by this error handling logic and my ELMAH has been getting populated with hundreds of pointless errors. More annoyingly, it makes debugging painful to have to keep F5-ing the errors. These resources are: favicon.ico, Error.aspx (my custom error page), and some images in a particular folder.
So I followed the advice of this post, and attempted to solve the issues through ignoring routes in the global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("elmah.axd");
routes.IgnoreRoute("/Content/images/{*pathinfo}"); // This has succesfully rid me of a bunch of errors
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); // This has successfully rid me of the favicon error
routes.IgnoreRoute("{*allaspx}", new { allaspx = #"(.*/)?.aspx(/.*)?" }); // NOT SURE OF THIS ONE
...
);
}
As I've mentioned in the comments, this has cleared up many of the errors. The problem I now have is that when I start the application, I'm immediatley given a 404 screen of death, telling me my custom error page cannot be found. The error details:
System.Web.HttpException (0x80004005): The file '/Error.aspx' does not exist.
at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp)
at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)
at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
And the web config section:
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx" />
...
</system.web>
The error page was working just fine before I made the changes to the routing. If I comment out the /content/images path - the app works again (though I'm back to "The controller for path '{0}' could not be found or it does not implement IController" errors). Commenting out the favicon or allaspx route has no change on this 404 error.
Any help would be greatly appreciated.
Cheers,
Tim.

The issue was badly setup error page.
I went back to the very beginning, and this tutorial. I did not have an ErrorController and was using the HandleError attribute. Following the instructions in this link fixed it up the problems with the error page. The answer to ignore routes worked for the favicon. The other files were genuinely missing files.

We got the same error message, but issue was different, the optional parameter we were passing contains / character, which causes the application to look for different routing. So please verify that your parameter doesn't contain / character.

Related

System exception occurred during an invocation on EJB caused by illegal argument exception

I'm not too sure what is wrong with it. It keeps on showing these error messages. Seems like there are some null values but i can't seem to identify and correct those issues. Can anyone help to take a look?
Update: I'm thinking the issue should either in the managedbean or post construct method but i can't seem to find out why..
Summarized Error Message
System exception occurred during an invocation on EJB RequestController,
method: public entity.Request ejb.session.stateless.RequestController.retrieveRequestByRequestId(java.lang.Long) throws exception.RequestNotFoundException
Caused by: java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation.
Post Construct In DeleteRequestManagedBean
#PostConstruct
public void postConstruct() {
requestId = (Long)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("request");
try {
request = requestControllerLocal.retrieveRequestByRequestId(requestId);
}
//Removed some irrelevant codes
Delete Request Method In DeleteRequestManagedBean
public void deleteRequest() {
requestControllerLocal.deleteRequest(requestId);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Request has been successfully deleted: ", null));
}
Button to delete request in xhtml
<p:commandButton value="Remove" icon ="fa fa-fw fa-remove" styleClass="p-btnDelete" actionListener="#{deleteRequestManagedBean.deleteRequest}"/>
Delete Request Method in RequestController (Stateless Sessionbean)
#Override
public void deleteRequest(Long requestId) throws RequestNotFoundException, DeleteRequestException {
//Removed some irrelevant codes
Request requestToDelete = retrieveRequestByRequestId(requestId);
requestToDelete.getCategory().getRequests().remove(requestToDelete);
em.remove(requestToDelete);
}
Please feel free to let me know if there are any other information you need. Thank you!
It turns out that both my managedbean and xhtml page has issues.
I have to use getAttribute() instead and get the attribute "postRToDelete" from the xhtml page. Without getting retrieving this, it keeps on giving me the null pointers, illegal argument exceptions.
Here it is for the benefit for those who made the same mistake as me.
DeleteRequestManagedbean
Request request = (Request) event.getComponent().getAttributes().get("postRToDelete");
xhtml page
<p:commandButton value="Delete" icon ="fa fa-fw fa-remove" styleClass="p-btnDelete" actionListener="#{profileManagedBean.deletePostedRequest}" update="#form">
<!--attribute from here-->
<f:attribute name="postRToDelete" value="#{postedReq}"/>
</p:commandButton>

CodeFluent persistence race condition

As soon as the database becomes slow for some reason ( long running query, backup, performance analyzer)
My Web Application start getting, eventually the following errors:
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at CodeFluent.Runtime.CodeFluentPersistence.InternalExecuteNonQuery(Boolean firstTry)
at CodeFluent.Runtime.CodeFluentPersistence.InternalExecuteNonQuery(Boolean firstTry)
.... _> stack trace continues to my code
CodeFluent.Runtime.CodeFluentRuntimeException: CF1044: Nested persistence command is not supported. Current command: '[Contract_Search]', nested command: '[zref_template_document_LoadBlobFile]'.
at CodeFluent.Runtime.CodeFluentPersistence.CreateStoredProcedureCommand(String schema, String package, String intraPackageName, String name)
at CodeFluent.Runtime.BinaryServices.BinaryLargeObject.GetInputStream(CodeFluentContext context, Int64 rangeStart, Int64 rangeEnd)
.... _> stack trace continues to my code
The second error CF1044 happens when I open two browser windows and doing different actions. Search in one, generate a document in another.
It's difficult to reproduce. It never happens the same way.
There is a race condition somewhere I can't figure out.
Here is what actually worked for me:
public byte[] GetRtfDocumentStreamBuffer(TemplateDocumentType templateType, int culture)
{
var template = TemplateDocument.LoadActiveByDocumentTypeAndLcid(DateTime.Today, templateType.Id, culture);
var resultStream = new MemoryStream();
using (var cf = CodeFluentContext.GetNew(Constants.MyApplicationStoreName))
using (var templateStream = template.File.GetInputStream(cf, 0, 0))
using (var resultWriter = new StreamWriter(resultStream, Encoding.GetEncoding("windows-1252")))
{
GenerateRtfDocument(....);
resultWriter.Flush();
}
return resultStream.GetBuffer();
}
what I saw in decompiled cf runtime that is CodeFluentContext.Dispose() call CodeFluentPersistence.Dispose() which close reader and dispose connection.

AppHarbor Error .NET 4.5 .asmx has not been pre-compiled, and cannot be requested

I would like this old school .asmx file to work with .NET 4.5 on AppHarbor but its giving me this error which I don't see locally. Any ideas?
Is it because I recently moved to target .NET 4.5? The rest of the app is fine.
.asmx has not been pre-compiled, and cannot be requested.
Here is some stack trace
System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +692
System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +103
System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate) +48
System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath) +16
In case anyone comes across this... I ended up re-writing the .asmx functionality (I only had one anyway) into WebApi which was on my to do list... so I just bumped it up to priority one and got rid of the old technology entirely.
Also of note was that I needed to add a .gitignore file to the root of my project which I ended up doing like this...
bin/*.dll
obj/*.dll
obj/Debug/*.dll
obj/Debug/TempPE/*.dll

Error in mockito when method

I'm just trying to stub the method but getting null pointer exception. I'm kinda blank what's going on here.
my method :
OauthStatus validate(HttpServletRequest request,
boolean accessTokenRequired) throws OauthProviderException;
and Stub is :
Mockito.when(oauthProviderMock.validate((MockHttpServletRequest) Mockito.anyObject(), (boolean)Mockito.anyBoolean())).
thenReturn(new OauthStatus());
i see there is no wrong in mocking but throws nullpointer exception.
Any idea what's going on here?
Remove your casts to (MockHttpServletRequest) and (boolean) so it looks like this
Mockito.when(oauthProviderMock.validate(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean())).
thenReturn(new OauthStatus());
According to the anyObject API it will return null so you are probably seeing your NPE here.
According to the anyBoolean API it will return false so there should be no need to cast.
Work around is Mocked the method through programmatically by using anonymous class instead of Mockito.
ex:
oauthProvider = new OauthProvider(){
validate( HttpServletRequest req, boolean flag) throws Exception{
throw new RuntimeException();
}
};

Clientside error (Cannot call method 'nullMethod' of null arguments: nullMethod)

My App engine/ GWT project is spitting out a nasty little pile of stack trace whenever it attempts to return from my login method. I am using GAE version 1.5.0 and GWT version 2.3.0 .
It's a facebook app, so what I've got is this:
The player navigates to the app page.
They click a button, and are redirected to the OAuth authentication page
They are then redirected back to the app, with the authentication token in the query string
I break the query string apart to get the UID, and then use that as the primary key for my Player entity (RPC to app engine backend)
I retrieve the Player entity instance from the datastore, and turn it into a serializable type to return to the client
Epic fail.
When I spit out the exception in a JSAlert, I get a big nasty pile of stack trace (I already was thoughtful enough to compile using "pretty" instead of "obfuscated").
My login function looks like this:
#Override
public ClientPlayer login(String uid) {
PersistenceManager pm=PMF.get().getPersistenceManager();
log.warning(Player.class.getName());
log.warning(uid);
Key k=KeyFactory.createKey(Player.class.getSimpleName(), uid);
Player p;
List<List<Integer>> stats;
try{
p=pm.getObjectById(Player.class, k);
} catch (JDOObjectNotFoundException e){
p=new Player(uid);
p.setKey(k);
pm.makePersistent(p);
} finally {
pm.close();
}
stats=p.getStats();
return new ClientPlayer(p.getUID(),p.getPerm(), p.getDecks(),stats.get(0), stats.get(1), stats.get(2));
}
Unfortunately, due to NDA, I can't link to the app, but here's the output:
Failure to log in because of:
com.google.gwt.core.client.JavaScriptException: (TypeError): Cannot call method 'nullMethod' of null
arguments: nullMethod,
type: non_object_property_call
stack: TypeError: Cannot call method 'nullMethod' of null
at Object.ClientPlayer_1 (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:993:89)
at Object.ClientPlayer_0 (http://*com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:984:18)
at Array.instantiate_1 [as 0] (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:1031:10)
at $instantiate_0 (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:10660:34)
at $instantiate (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:1948:10)
at $readObject (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:10148:95)
at Object.read_8 [as read] (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:10608:10)
at $onResponseReceived (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:10352:247)
at $fireOnResponseReceived (http://*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:5002:5)
at Object.onReadyStateChange (http:/*.com/com.MES.Tap2/A37A2E2E9A65DB1BAAE2BFA42572F7F8.cache.html:5222:5)
The issue was in the use of the IsSerializable interface, or rather my poor understanding of it.
When you create an IsSerialiazable object, it requires a no-argument constructor. I was passing null values from that constructor to the main constructor, so when methods were called on them, null pointer exceptions occurred. This was dumb of me, but hey, it was a learning experience.
In my particular case, it went a little like this...
public class ClientObject implements IsSerializable {
private Object field1;
private Object field2;
private String field3;
public ClientObject(){
this(null, null);
}
public ClientObject(Object arg1, Object arg2){
field1=arg1;
field2=arg2;
field3=arg1.toString()+arg2.toString();
//Error on above line, though not obviously mentioned in the message
}
}
What should have been done was...
public ClientObject(){
this(new Object(), new Object());
}
Hope this helps someone.