handle some errors in Global.asax - asp.net-mvc-3

I have a web application on .NET4 and MVC3 (razor) .
I want to handle my application errors in Global.asax. I have created application_error function.
I have noticed and found some errors.
one of them returns this string in Application_Error when I am trying to add break point on line Response.Clear(); and that error is generic.
how can I find which codes or part of my codes makes it?
my code:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
}
error on httpException:
{System.Web.HttpException (0x80004005): File does not exist.
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String
physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String
overrideVirtualPath)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context,
AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt
ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)}

i found the solution
string errorLocation = Request.Path;
this syntax in Application_Error() tel you where is the problem :)

Just to state my experience with this exception, in my case the reason was that there was no webpage specified as the start page for the site.

Related

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

Xamarin Android Httppost Request

I am trying to make a post call to my web Api which is on local host. But I am getting following error
result = {System.Net.WebException: The remote server returned an
error: (415) Unsupported Media Type. at
System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult
asyncResult) [0x0005e] in
/Users/builder/data/lanes/3511/f4db8a57/source/mono/mcs/class/System/Sy...
Can anyone help? Below is my code:
private void click (Object sender, EventArgs e)
{
UserInfo user = new UserInfo(1, "hellohello#gmail.com", "helloss");
String data = JsonConvert.SerializeObject(user);
WebClient wc = new WebClient();
wc.UploadStringAsync(new Uri("http://192.168.206.2:155/api/register"), data);
wc.UploadStringCompleted += Wc_UploadStringCompleted;
}
private void Wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var result = e.Error;
}
So far, the Server only get's a string from you and can't know if, it is json, xml or something else. You just have to tell him.
You can to this on a WebClient via:
wc.Add("Content-Type", "aplication/json");
If you are using the HttpClient you have to set ist via the Content property:
request.Content = new StringContent("json", Encoding.UTF8, "application/json");
The HTTP specification states:
415 Unsupported Media Type
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method. The format problem might be due to the request's indicated Content- Type or Content-Encoding, or as a result of inspecting the data directly.
It seems your server is having troubles with the format... try adding the headers with .Add("Accept", "aplication/json");

ServiceStack : How to catch errors before written to response

I develop a Rest Service by using ServiceStack.
My model contains a DateTime property and the problem start with it.If a client post/get wrong formatted date value as string , ServiceStack fires an exception "String was not recognized as a valid DateTime."
Stack Trace:
[FormatException: String was not recognized as a valid DateTime.]
System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) +6364458
ServiceStack.Text.Common.DeserializeBuiltin`1.<GetParseFn>b__b(String value) in C:\src\ServiceStack.Text\src\ServiceStack.Text\Common\DeserializeBuiltin.cs:58
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:79
[SerializationException: KeyValueDataContractDeserializer: Error converting to type: String was not recognized as a valid DateTime.]
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:95
ServiceStack.ServiceHost.RestPath.CreateRequest(String pathInfo, Dictionary`2 queryStringAndFormData, Object fromInstance) in C:\src\ServiceStack\src\ServiceStack\ServiceHost\RestPath.cs:319
ServiceStack.WebHost.Endpoints.RestHandler.GetRequest(IHttpRequest httpReq, IRestPath restPath) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:104
ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:80
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +625
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I know its an error and I know it must be catches but I want to implement it with my error codes and error descriptions(human friendly).
Any advice could be very helpful about how to catch an exception before its written to response itself on (DebeugMode=true) or the service fires an exception to client.
Thnx
Add your Custom Request Binder (or more advanced option is to implement IRequiresRequestStream on your DTOs) to by-pass ServiceStack's deserialization with your own.
More information about this is contained in ServiceStack's wiki documentation

ApiController Routing Isn't Working

Below I'm going to insert the code for the following:
Global.asax
DatabasesController (ApiController)
The error I receive when trying to navigate to the default api route.
It is my understand that what I'm doing here is 100% correct, and in fact I've verified that the code lines up with an example I found from Mike Wasson. Hopefully you can show me the way to getting this working!
Thanks all!
Global.asax
Below is the code that exists in the Global.asax and this method is called by Application_Start() which was generated by the template.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
DatabasesController.cs
This is the ApiController, and it inherits from ApiController and was created by the template in Visual Studio. The databases field is declared as Database[] in the class.
public IEnumerable<Database> GetAllDatabases()
{
return databases;
}
public Database GetDatabaseById(string id)
{
return databases.Where(d => d.Name == id).FirstOrDefault();
}
Error
This is the error I'm receiving when I try to access it with what should be the default api path (as far as I understand it anyway...HA).
Server Error in '/' Application.
--------------------------------------------------------------------------------
Method not found: 'Void System.Net.Http.Headers.HttpHeaders.AddWithoutValidation(System.String, System.Collections.Generic.IEnumerable`1<System.String>)'.
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.MissingMethodException: Method not found: 'Void System.Net.Http.Headers.HttpHeaders.AddWithoutValidation(System.String, System.Collections.Generic.IEnumerable`1<System.String>)'.
Source Error:
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.
Stack Trace:
[MissingMethodException: Method not found: 'Void System.Net.Http.Headers.HttpHeaders.AddWithoutValidation(System.String, System.Collections.Generic.IEnumerable`1<System.String>)'.]
System.Web.Http.WebHost.HttpControllerHandler.AddHeaderToHttpRequestMessage(HttpRequestMessage httpRequestMessage, String headerName, String[] headerValues) +0
System.Web.Http.WebHost.HttpControllerHandler.ConvertRequest(HttpContextBase httpContextBase) +248
System.Web.Http.WebHost.HttpControllerHandler.BeginProcessRequest(HttpContextBase httpContextBase, AsyncCallback callback, Object state) +79
System.Web.Http.WebHost.HttpControllerHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +268
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It looks like you need to upgrade your version of webapi from beta to RC!

WebRequestExtensions.GetCurrentNetworkInterface throws InvalidOperationException

I want to get Network Interface on which HttpWebRequest was made
I found WebRequestExtensions.GetCurrentNetworkInterface function for this. HttpWebRequest also has GetCurrentNetworkInterface() method to perform the same.
This is my code:
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(new Uri(Url, UriKind.Absolute));
//this line throws InvalidOperationException
NetworkInterfaceInfo i = httpWebRequest.GetCurrentNetworkInterface();
I perform method call from UI thread. If I made call after BeginGetResponse exception tells "request was finished". What is workaround for this?
Exception info:
Message is InvalidOperationException
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.GetConnectionDetails(IntPtr& Details, Int32& sizeofDetails)
at Microsoft.Phone.Net.NetworkInformation.WebRequestExtensions.GetCurrentNetworkInterface(WebRequest request)
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(new Uri(Url, UriKind.Absolute));
httpWebRequest.BeginGetResponse(result =>
{
// Handle response
}, null);
var info = WebRequestExtensions.GetCurrentNetworkInterface(httpWebRequest);
I had a similar problem recently and found you can't call GetCurrentNetworkInterface before BeginGetResponse (because the connection hasn't been made) but if you call it within the BeginGetResponse callback the request has already completed and you get the "Web request is already finished" error.
ADDED by question-starter:
Fully-worker code which allows to get NetworkInterfaceInfo of HttpWebRequest from background thread (used BackgroundWorker in this example to simulate this):
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, 4) =>
{
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(new Uri("http://stackoverflow.com", UriKind.Absolute));
EventWaitHandle Wait = new AutoResetEvent(false);
httpWebRequest.BeginGetResponse(result =>
{
Wait.Set();
}, null);
Wait.WaitOne();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var info = WebRequestExtensions.GetCurrentNetworkInterface(httpWebRequest);
MessageBox.Show(info.InterfaceType.ToString());
});
};
backgroundWorker.RunWorkerAsync();
ADDED AFTER FULL-DAY DEBUGGING:
I can't make it work 100% time, especially when loaded page is small. In this situation "request is finished" appears all the time. But with large loaded page it works even without EventWaitHandle
I beleive you might want to take a look at the NetworkInterface.NetworkInterfaceType Property. The documentation says that it returns the Interface type that is servicing current internet requests.
If this is not what you are looking for, you might also want to try the DeviceNetworkInformation class(I suspect you might have already looked at this option.). I think you could use the IsCellularDataEnabled and The IsWifiEnabled static properties.

Resources