I built up this regex at http://regextester.com to parse YSOD but VS is complaining about a syntax error. I am sure I am missing an escape somewhere but I am coming up blank.
Here is is in original form. any help is appreciated.
var rxYSOD = /<!--\s*\[(.*?)]:(\s*.*\s(.*\n)*?)\s*(at(.*\n)*)-->/gs;
UPDATE:
Kobi pointed out the obvious and got me moving again. For those who are interested, this is valid JavaScript to test and parse an XMLHttpRequest.responseText for an ASP.net Yellow Screen Of Death (YSOD).
var rxYSOD = /<!--\s*\[(.*?)]:(\s*.*\s(.*[\n\r]*)*?)\s*(at(.*[\n\r]*)*)-->/;
if (rxYSOD.test(text)) {
// looks like one..
var ysod = rxYSOD.exec(text);
errObj = { Message: ysod[2], StackTrace: ysod[4], ExceptionType: ysod[1] };
}
#Kobi - This is the result and the reason I want to parse the html even though I get a 500:
{
"message": " Unknown web method ValidateUser.\r\nParameter name: methodName\r\n",
"stackTrace": "at System.Web.Script.Services.WebServiceData.GetMethodData(String methodName)\r\n at System.Web.Script.Services.RestHandler.CreateHandler(WebServiceData webServiceData, String methodName)\r\n at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)\r\n at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)\r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)\r\n",
"exceptionType": "ArgumentException",
"errorObject": {
"Message": " Unknown web method ValidateUser.\r\nParameter name: methodName\r\n",
"StackTrace": "at System.Web.Script.Services.WebServiceData.GetMethodData(String methodName)\r\n at System.Web.Script.Services.RestHandler.CreateHandler(WebServiceData webServiceData, String methodName)\r\n at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)\r\n at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)\r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)\r\n",
"ExceptionType": "ArgumentException"
},
"statusCode": 500,
"servicePath": "/Authentication_JSON_AppService.axd",
"useGet": false,
"params": {
"username": "testingUser",
"password": "testingUser",
"customCredential": null
},
"methodName": "ValidateUser",
"__typeName": "Salient.ScriptModel.WebServiceError"
}
Firefox says:
Error: invalid regular expression flag s
Source Code:
var rxYSOD = /<!--\s*\[(.*?)]:(\s*.*\s(.*\n)*?)\s*(at(.*\n)*)-->/gs;
After removing the s it seems ok (of course, it isn't tested, just parsed correctly).
The flag s is invalid in Javascript. To replace, use the replace method.
Related
While uploading a file to rackspace cloud using the CreateObjectFromFile method from my local machine, it goes though fine. but when i do it from a client machine i get net.openstack.Core.Exceptions.Response.BadServiceRequestException.
ContainerID: 1644
srcfileName: \\10.5.48.2\XMLGateway\BOOutBox\PJR340131023160359529217.xml
desfileName: 1644_PJR340131023160359529217.xml
cloudFilesProvider.CreateObjectFromFile(inStrContainerID, inStrSrcFilePath, strDesFileName);
I checked for documentation on this exception and i cannot find anything useful.
EDIT:
here is the error stack
net.openstack.Core.Exceptions.Response.BadServiceRequestException: Invalid request body: unable to parse Auth data. Please review XML or JSON formatting.
at net.openstack.Providers.Rackspace.Validators.HttpResponseCodeValidator.Validate(Response response)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.ExecuteRESTRequest[T](CloudIdentity identity, String urlPath, HttpMethod method, Object body, Dictionary`2 queryStringParameter, Boolean isRetry, Boolean isTokenRequest, String token, Int32 retryCount, Int32 retryDelay, Func`7 callback)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.ExecuteRESTRequest[T](CloudIdentity identity, String urlPath, HttpMethod method, Object body, Dictionary`2 queryStringParameter, Boolean isRetry, Boolean isTokenRequest, String token, Int32 retryCount, Int32 retryDelay)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.<>c__DisplayClassc.<GetUserAccess>b__b()
at net.openstack.Core.Caching.UserAccessCache.<>c__DisplayClassc.<Get>b__4(String k)
at System.Collections.Concurrent.ConcurrentDictionary`2.AddOrUpdate(TKey key, Func`2 addValueFactory, Func`3 updateValueFactory)
at net.openstack.Core.Caching.UserAccessCache.Get(String key, Func`1 refreshCallback, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.GeographicalCloudIdentityProvider.GetUserAccess(CloudIdentity identity, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.CloudIdentityProvider.GetUserAccess(CloudIdentity identity, Boolean forceCacheRefresh)
at net.openstack.Providers.Rackspace.ProviderBase`1.GetServiceEndpoint(CloudIdentity identity, String serviceName, String region)
at net.openstack.Providers.Rackspace.ProviderBase`1.GetPublicServiceEndpoint(CloudIdentity identity, String serviceName, String region)
at net.openstack.Providers.Rackspace.CloudFilesProvider.GetServiceEndpointCloudFiles(CloudIdentity identity, String region, Boolean useInternalUrl)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObject(String container, Stream stream, String objectName, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObjectFromFile(String container, String filePath, String objectName, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at ?.?.?(String ?, String ?, String ?, String ?, String ?, String& ?, Boolean& ?, String& ?)
Edit 2:
Ok after updating the dll to the new versions, this is the stacktrace:
Unable to connect to the remote server
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.203.3.30:443
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.<>c__DisplayClass6.<Stream>b__5(HttpWebRequest req)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.<>c__DisplayClass9.<ExecuteRequest>b__8()
at JSIStudios.SimpleRESTServices.Client.RequestRetryLogic.Execute(Func`1 callback, IEnumerable`1 non200SuccessCodes, Int32 retryCount, Nullable`1 retryDelay)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.ExecuteRequest(Uri url, HttpMethod method, Func`3 responseBuilderCallback, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Func`2 executeCallback)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.Stream(Uri url, HttpMethod method, Func`3 responseBuilderCallback, Stream content, Int32 bufferSize, Int64 maxReadLength, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Action`1 progressUpdated)
at JSIStudios.SimpleRESTServices.Client.RestServiceBase.Stream(Uri url, HttpMethod method, Stream content, Int32 bufferSize, Int64 maxReadLength, Dictionary`2 headers, Dictionary`2 queryStringParameters, RequestSettings settings, Action`1 progressUpdated)
at net.openstack.Providers.Rackspace.ProviderBase`1.StreamRESTRequest(CloudIdentity identity, Uri absoluteUri, HttpMethod method, Stream stream, Int32 chunkSize, Int64 maxReadLength, Dictionary`2 queryStringParameter, Dictionary`2 headers, Boolean isRetry, RequestSettings requestSettings, Action`1 progressUpdated)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObject(String container, Stream stream, String objectName, String contentType, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at net.openstack.Providers.Rackspace.CloudFilesProvider.CreateObjectFromFile(String container, String filePath, String objectName, String contentType, Int32 chunkSize, Dictionary`2 headers, String region, Action`1 progressUpdated, Boolean useInternalUrl, CloudIdentity identity)
at ?.?.?(String ?, String ?, String ?, String ?, String ?, String& ?, Boolean& ?, String& ?
So does have to do with with firewall settings on the client machine?
A newer release of the SDK is available through NuGet. Two of the many changes included in that release are the following:
Removed GeographicalCloudIdentityProvider (a class only used inside the SDK itself, nevertheless this is the part of your stack trace that indicated you were using an old version of the SDK)
Added the ability for ResponseException (the base class of BadServiceRequestException and several others) to include detailed information about the cause of the problem as part of the exception.
(Applies to openstack.net 1.2.x only): Due to a limitation in the SDK dependencies that we are working to resolve ASAP, you'll need to explicitly install one of the SDK dependencies before installing the SDK. The instructions for this are included in the comment marked UPDATE on the following page: openstacknetsdk/openstack.net#203
I am writing IHttpModule to allow friendly URL access to our one of the detail page. When user is trying to access detail page using http://xyx.com/hotels/123/hotel-name.aspx page, re-write rule is going to applied in IHttpModule's OnBeginRequest method.
Here, I wrote to change path to "~/DetailPages/DetailPage.aspx" using Context.RewritePath("~/DetailPages/DetailPage.aspx", "", "Code=123"), where 123 is code taken from Original URL.
Now if original URL does not contain any query string, Detail page is getting invoked. But when user is trying to access http://xyz.com/hotels/123/hotel-name.aspx?show=advance then re-write code will be executed as Context.RewritePath("~/DetailPages/DetailPage.aspx", "", "Code=123&show=advance"). Here we are getting an error saying "/hotels/123/hotel-name.aspx" page does not existing.
Before & After Calling "Context.RewritePath" method, I have taken details from Context.Request object that is given below. Both looks perfect and same if there is no Query string in original URL. But when Original URL contains query string, Inside "Context_Error" (an event to listen any error for this request execution) method, when getting Server.GetLastError() says "/hotels/123/hotel-name.aspx" page does not existing.
Please refer below trace detail from Context.Request object. Your help/inputs are welcome as i have spent 8 hrs already without any positive result.
---------------------------
Before - RewritePath Call
---------------------------
RawUrl : - /Hotels/123/hotel-name.aspx?a=b
AppRelativeCurrentExecutionFilePath : - ~/Hotels/123/hotel-name.aspx
CurrentExecutionFilePath : - /Hotels/123/hotel-name.aspx
Params : - a=b&__utma=221736730.1213284380.1356606190.1356674469.1356687004.4.....(Windows+NT+5.1%3b+rv%3a7.0.1)+Gecko%2f20100101+Firefox%2f7.0.1
Path : - /Hotels/123/hotel-name.aspx
PhysicalPath : - D:\AppRoot\Hotels\161\hotel-name.aspx
Url : - http://xyz.com/Hotels/123/hotel-name.aspx?a=b
---------------------------
After - RewritePath Call
---------------------------
RawUrl : - /Hotels/123/hotel-name.aspx?a=b
AppRelativeCurrentExecutionFilePath : - ~/DetailPages/DetailPage.aspx
CurrentExecutionFilePath : - /DetailPages/DetailPage.aspx
Params : - Code=123&a=b&__utma=221736730.1213284380.1356606190.1356674469.1356687004.4.....(Windows+NT+5.1%3b+rv%3a7.0.1)+Gecko%2f20100101+Firefox%2f7.0.1
Path : - /DetailPages/DetailPage.aspx
PhysicalPath : - D:\AppRoot\DetailPages\DetailPage.aspx
Url : - http://xyz.com/DetailPages/DetailPage.aspx?Code=123&a=b
---Server.GetLastError - Trace - Inside IHttpModule's Error Event--
RawUrl : - /Hotels/123/hotel-name.aspx?a=b
AppRelativeCurrentExecutionFilePath : - ~/Hotels/123/hotel-name.aspx
CurrentExecutionFilePath : - /Hotels/123/hotel-name.aspx
Params : - a=b&__utma=221736730.1213284380.1356606190.1356674469.1356687004.4....(Windows+NT+5.1%3b+rv%3a7.0.1)+Gecko%2f20100101+Firefox%2f7.0.1
Path : - /Hotels/123/hotel-name.aspx
PhysicalPath : - D:\AppRoot\Hotels\161\hotel-name.aspx
Url : - http://xyz.com/Hotels/123/hotel-name.aspx?a=b
Error Message
The file '/Hotels/123/hotel-name.aspx' does not exist.
Stack Trace
at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert)
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)
Can anyone find out what could be an issue?
Thanks in advance.
There was another IHttpModule changing URL when found Query String in Original URL. Hence I get what I need.
Thank you all for your kind suggestions and interest.
When i try to execute the following script..i get an error .I am trying to receive data using JSON.
function loadData() {
isLoading = true;
$('#loaderCircle').show();
alert("OOOOO");
$.ajax({
url: apiURL,
dataType: 'json',
data: { page: page }, // Page parameter to make sure we load new data
success: function(data) {
isLoading = false;
$('#loaderCircle').hide();
// Increment page index for future calls.
page++;
// Create HTML for the images.
var html = '';
var i = 0, length = data.length, image;
alert(data.length);
for (; i < length; i++) {
image = data[i];
html += '<li class="polaroid"><div class="optionbg"></div><div class="optionback"><span>Necklaces</span></div><div class="options"><span class="favs">14</span><span class="fav">like it!</span></div><img src="' + image.preview + '" width="180" height="' + Math.round(image.height / image.width * 180) + '"></li>';
}
// Add image HTML to the page.
$('#tiles').append(html);
// Apply layout.
applyLayout();
},
error: function(result) {
$('#qqq').text(JSON.stringify(result));
//alert(JSON.stringify(result));
}
});
};
Webservice:
<WebMethod(Description:="Gets the Categories")> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetCategories() As String
Dim details As New List(Of Nodes)()
Using ds As Data.DataSet = db.ExecuteDataSet(CommandType.Text, "SELECT NodeID,NodeName FROM Nodes WHERE ParentID='1'")
Dim JaggedArray As String()() = New String(ds.Tables(0).Rows.Count - 1)() {}
Dim i As Integer = 0
For Each rs As DataRow In ds.Tables(0).Rows
Dim node As New Nodes()
node.NodeId = rs("NodeId").ToString
node.NodeName = rs("NodeName").ToString
details.Add(node)
'JaggedArray(i) = New String() {rs("NodeName").ToString(), rs("NodeID").ToString()}
i = i + 1
Next
End Using
Dim js As New JavaScriptSerializer()
Dim strJSON As String = js.Serialize(details.ToArray)
Return strJSON
End Function
JSON Output:
<string xmlns="http://localhost:54511/">
[{"NodeId":"BK01","NodeName":"Books","ParentId":null,"Likes":null},{"NodeId":"CO01","NodeName":"Computers","ParentId":null,"Likes":null},{"NodeId":"GA01","NodeName":"Gaming","ParentId":null,"Likes":null},{"NodeId":"MO01","NodeName":"Mobile & Accessories","ParentId":null,"Likes":null}]
</string>
Error:
{"readyState":4,"responseText":"<html>\r\n <head>\r\n <title>Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.</title>\r\n <style>\r\n body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n pre {font-family:\"Lucida Console\";font-size: .9em}\r\n .marker {font-weight: bold; color: black;text-decoration: none;}\r\n .version {color: gray;}\r\n .error {margin-bottom: 10px;}\r\n .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n </style>\r\n </head>\r\n\r\n <body bgcolor=\"white\">\r\n\r\n <span><H1>Server Error in '/EntLib5' Application.<hr width=100% size=1 color=silver></H1>\r\n\r\n <h2> <i>Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.</i> </h2></span>\r\n\r\n <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n <b> Description: </b>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.\r\n\r\n <br><br>\r\n\r\n <b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.<br><br>\r\n\r\n <b>Source Error:</b> <br><br>\r\n\r\n <table width=100% bgcolor=\"#ffffcc\">\r\n <tr>\r\n <td>\r\n <code>\r\n\r\nAn unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>\r\n\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <br>\r\n\r\n <b>Stack Trace:</b> <br><br>\r\n\r\n <table width=100% bgcolor=\"#ffffcc\">\r\n <tr>\r\n <td>\r\n <code><pre>\r\n\r\n[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.]\r\n System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405913\r\n System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212\r\n System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47\r\n System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193\r\n System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93\r\n System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155\r\n</pre></code>\r\n\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <br>\r\n\r\n <hr width=100% size=1 color=silver>\r\n\r\n <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4971; ASP.NET Version:2.0.50727.4971\r\n\r\n </font>\r\n\r\n </body>\r\n</html>\r\n<!-- \r\n[InvalidOperationException]: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.\r\n at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)\r\n at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)\r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)\r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)\r\n-->","status":500,"statusText":"Internal Server Error"}
Mey be here you can find the solution: http://aspadvice.com/blogs/ssmith/archive/2007/09/04/FIX-Request-format-is-unrecognized-for-URL-unexpectedly-ending-in.aspx
This is the error I'm getting using MVC2:
Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.
It is coming from the [Required] Validation DataAnnotation.
Stack trace:
InvalidOperationException: Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.]
System.ComponentModel.DataAnnotations.ValidationAttribute.SetupResourceAccessor() +89338
System.ComponentModel.DataAnnotations.ValidationAttribute.FormatErrorMessage(String name) +38
System.Web.Mvc.<Validate>d__1.MoveNext() +215
System.Web.Mvc.<Validate>d__5.MoveNext() +735
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +424
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +732
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +475
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +152
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
I've boiled my view model down to this(it breaks any time there is a [Required] attribute, works fine without):
[Required(ErrorMessage = "")]
[DataType(DataType.Text)]
[DisplayName("Property Name")]
public string MyProperty { get; set; }
My controller returns an empty ViewModel, and the form in the view is completely blank...just a submit button.
In my case, I have write ErrorMessage = null, example :
[EmailAddress(ErrorMessageResourceName = "FORM_FIELD_VALIDATION_EMAIL", ErrorMessageResourceType = typeof(App_GlobalResources.Common.View_Common_Forms), ErrorMessage = null)]
ErrorMessage = " " don't work.
The problem lies in setting the ErrorMessage to a blank string. I would have to assume that at some point there is a check for String.Empty in the MVC code that is causing problems.
Setting the ErrorMessage to " "(one space) solved the issue.
My guess is [DataType(DataType.Text)] has a validation message defined in resources (in System.ComponentModel.DataAnnotations.Resources) and the existence of that and your [Required] is causing this InvalidOperationException. Try Removing [DataType] or [Required] and see if the exception goes away.
I had a simmilar issue with a custom ValidationAttribute.
In the IsValid method I was setting the ErrorMessage. The fix was to remove the assignation to the ErrorMessage propety...
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//code before ...
this.ErrorMessage = this.FormatErrorMessage(validationContext.DisplayName); //NOT GOOD...
ValidationResult validationResult = new ValidationResult(this.ErrorMessage, //And using the ErrorMessage Here...
new[] { validationContext.MemberName });
return validationResult;
}
I was writting Unit test and they were pasisng only if i was running/debugging one by one. But when I click "Run All", only the first one was passing? They are not Linked in any ways...
I also tried https://stackoverflow.com/a/20848920/4798459
Didn't work either.
So yeah, the fix was to remove the assignation to the ErrorMessage propety!
All of the sudden all of the calls to my web services get this error:
2010-11-04 17:42:16,321 [9] ERROR ABCKiosk - System.InvalidOperationException: Response is not well-formed XML. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ABCKiosk.WebServices.Services.ActivityLog(String kioskID, String KTID, String activityType, Int32 errorCodeFromIncentOne, String msgFromIncentOne, DateTime kioskTime) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\Web References\WebServices\Reference.cs:line 121
at ABCKiosk.FrmMain.FrmMain_KeyUp(Object sender, KeyEventArgs e) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\FrmMain.cs:line 110
Before every were fine :( anyone know where is the problem and how to solve this?
Many thanks!
UPDATE - PROVIDE MORE INFORMATION
Here is one of my web methods:
[WebMethod(EnableSession = true)]
public CommonResult ActivityLog(string kioskID, string KTID,
string activityType, int errorCodeFromIncentOne, string msgFromIncentOne, DateTime kioskTime)
{
XMLParser parser = new XMLParser(Server.MapPath(Constant.XML_CONFIGURATION_FILE_PATH));
CommonResult result = new CommonResult();
try
{
AccountDAO accountDAO = new AccountDAO();
ActivityLogDAO activityLogDAO = new ActivityLogDAO();
KioskDAO kioskDAO = new KioskDAO();
// check if this kiosk is existed
if (!kioskDAO.IsKioskIDExisted(kioskID))
{
result.ErrorCode = Constant.ERROR_CODE_KIOSKID_NOT_EXISTED;
result.Message = "abc";
return result;
}
// check if this KTID is existed
if (!accountDAO.IsKTIDExisted(KTID))
{
result.ErrorCode = Constant.ERROR_CODE_KTID;
result.Message = "abc";
return result;
}
// check if this customer already logged for today
if (activityLogDAO.IsLoggedForToday(KTID, DateTime.Now))
{
result.ErrorCode = Constant.ERROR_CODE_LOG_LIMIT;
result.Message = "abc";
return result;
}
// begin log this activity to database
activityLogDAO.ActivityLog(KTID, kioskID, kioskTime);
// return success
result.ErrorCode = Constant.ERROR_CODE_SUCCESS;
result.Message = "abc";
return result;
}
catch (Exception e)
{
result.ErrorCode = Constant.ERROR_CODE_SYSTEM_ERROR;
result.Message = "abc";
return result;
}
}
UPDATE
I tried running the webmethod locally, inspected the return page and saw this in the page source:
<b> Description: </b>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.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405913
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193
System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</pre></code>
I found out the bug myself, all because of a single line Response.Write() in the Session_Start() that mess up everything :(