HTTP/1.1 500 Internal Server Error in ASP.Net - c#

I have published my website to hosting but i got the problem "HTTP/1.1 500 Internal Server Error" and my website shows "Error. An error occurred while processing your request"
I turned off customError mode and this is what it shows
Server Error in '/' Application. Invalid URI: The format of the URI
could not be determined. 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.UriFormatException: Invalid URI: The format
of the URI could not be determined.
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: [UriFormatException: Invalid URI: The format of the URI could not be determined.] System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) +8516254 System.Net.WebRequest.Create(String requestUriString) +44 CheckWebsite.Controllers.HomeController.WebRequestTest(String url) in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:111 CheckWebsite.Controllers.HomeController.Index() in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:26 lambda_method(Closure , ControllerBase , Object[] ) +87 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +35
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult
asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +77 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +69 System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +80 System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +387 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +69 System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +50 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +59 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38 System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+602 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously) +128`
And I checked the server log and it says "500 GET / - HTTP/2"
How can I resolve this situation and get the website up and running?
My website works good when I try it on localhost but for some reason it can't run on the server.
I've seen some articles but I can't apply it.
And this is my code:
public static bool WebRequestTest(string url)
{
try
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
System.Net.WebResponse myResponse = myRequest.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
public ActionResult Index()
{
List<QLWebsite> obj = strDM.getDomain(0);
for (int i = 0; i < obj.Count; i++)
{
if (WebRequestTest(obj[i].Domain) == false)
{
obj[i].status = false;
strDM.EditDomain(obj[i]);
}
else
{
obj[i].status = true;
strDM.EditDomain(obj[i]);
}
}
return View(obj);
}

Related

Crystal report fails to load when application is deployed in IIS in ASP.net Mvc app

I get a error when after I published the app. Even on the same computer that I devolved on. While developing everything worked fine.
The system cannot find the path specified.
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.Runtime.InteropServices.COMException: The system cannot find the path specified.
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:
[COMException (0x80004005): The system cannot find the path specified.
]
CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(Object& DocumentPath, Int32 Options) +0
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.Open(Object& DocumentPath, Int32 Options) +126
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +315
[CrystalReportsException: Load report failed.]
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +503
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename, OpenReportMethod openMethod, Int16 parentJob) +1495
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename) +99
ProductionTracker.Web.Reports.CrystalReportGenerator.GenerateReportInPDF(DataTable tb, String reportName) in C:\Users\barry\source\repos\ProductionTracker.Web\ProductionTracker.Web\Reports\Controller\CrystalReportGenerator.cs:37
System.Web.Mvc.<>c__DisplayClass1.<WrapVoidAction>b__0(ControllerBase controller, Object[] parameters) +18
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +229
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +77
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128
I tried this https://stackoverflow.com/a/14602748/10852981 and I cant figure out where to add this in my mvc app.
I checked the permissions on the files and allowed to everyone.
I included the .rpt file in project.
Im not sure what else i should do.
This is the code I have for downloading the file
public static void GenerateReportInPDF(DataTable tb, string reportName)
{
using (var reportDocument = new ReportDocument())
{
var reportPath = HttpContext.Current.Server.MapPath("~/") + "Reports//" + reportName;
reportDocument.Load(reportPath);
reportDocument.Database.Tables[0].SetDataSource(tb);
reportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, HttpContext.Current.Response, false, reportName);
reportDocument.Close();
}
}
This line ProductionTracker.Web.Reports.CrystalReportGenerator.GenerateReportInPDF(DataTable tb, String reportName) in C:\Users\barry\source\repos\ProductionTracker.Web\ProductionTracker.Web\Reports\Controller\CrystalReportGenerator.cs:37
looks wrong because its from my development repo. But im not sure what to do about it.
I finally solved it. The reason i had the error was because it was saving it to the bin folder once published. So i needed to change the path accordingly. I added /bin/ to
var reportPath = HttpContext.Current.Server.MapPath("~/") + "Reports//" + reportName;
Like this
var reportPath = HttpContext.Current.Server.MapPath("~/bin/") + "Reports//" + reportName;
Then it worked!

MailKit SmtpClient error: The operation is not allowed on non-connected sockets

I'm having an issue connecting to a remote email provider using the following code:
MimeMessage message = new MimeMessage();
message.To.Add(new MailboxAddress("recipient#mydomain.com"));
message.From.Add(new MailboxAddress("sender#mydomain.com", "sender#mydomain.com"));
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "htmlbody<br />";
bodyBuilder.TextBody = "textbody";
message.Body = bodyBuilder.ToMessageBody();
message.Subject = "Subject";
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("send.one.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
client.Authenticate("sender#mydomain.com", "***");
client.Send(message);
client.Disconnect(true);
}
I have confirmed that the settings are correct as they work on my dev machine. I have spoken to both the email provider and the hosting service, both of whom state that SMTP ports are open. The MailDNS SPF record should allow the connection. I also tried System.Net.Mail SmtpClient prior to MailKit, with the same results.
Does anyone have any experience of this issue? Advice on how to get this connection working would be greatly appreciated.
This is the error presented when the code is run on the deployed server (shared Arvixe IIS server).
Server Error in '/' Application.
The operation is not allowed on non-connected sockets.
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.IO.IOException: The operation is not allowed on non-connected sockets.
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:
[IOException: The operation is not allowed on non-connected sockets.]
System.Net.Sockets.NetworkStream.InitNetworkStream(Socket socket, FileAccess Access) +6762851
System.Net.Sockets.NetworkStream..ctor(Socket socket, Boolean ownsSocket) +44
MailKit.Net.Smtp.<ConnectAsync>d__70.MoveNext() +1110
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken) +55
MySolution.Functions.SendMail(MimeMessage message, Setting mail_settings) in C:\Users\Me\Documents\Visual Studio 2015\Projects\MySolution\MySolution\Functions.cs:401
MySolution.Functions.SendInstallationReport(Sale sale) in C:\Users\Me\Documents\Visual Studio 2015\Projects\MySolution\MySolution\Functions.cs:281
MySolution.Controllers.ReportsController.Sales(ViewText model, Sale record) in C:\Users\Me\Documents\Visual Studio 2015\Projects\MySolution\MySolution\Controllers\ReportsController.cs:236 lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
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) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
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) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9873665
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET
Version:4.7.3163.0

"The remote name could not be resolved" error when calling a Web Service in ASP.NET MVC, but a virtually identical unit test succeeds

I am receiving a System.Net.WebException with the message "The remote name could not be resolved" when trying to do a call to a Web Service with HttpClient in ASP.NET MVC. Bafflingly enough, I have a console application and accompanying unit test that has virtually identical code that works perfectly.
Here's the factory method that creates the HttpClient:
public HttpClient GetHttpClient(bool acceptVersion = true, string acceptType = #"application/json")
{
// This line was required to make this run without exception for
// my unit test
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string key = "key"; // Obviously, abbreviated
var client = new HttpClient();
if (acceptVersion)
{
client.DefaultRequestHeaders.Add("Accept-version", "beta");
}
client.DefaultRequestHeaders.Add("AccessToken", key);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptType) { CharSet = "utf-8" });
client.BaseAddress = new Uri("API uri"); // Obviously, edited
return client;
}
My factory method is literally line-for-line identical for my working unit test.
Here's the ASP.NET code:
public static async Task<double> PercentOfUsersCurrentlyActive()
{
string json;
using (var client = (new ConnectionFactory()).GetHttpClient(false))
{
// The exception occurs on this line
HttpResponseMessage message = await client.GetAsync("users");
json = await message.Content.ReadAsStringAsync();
}
UserCollection collection = JsonConvert.DeserializeObject<UserCollection>(json);
int numActive = collection.content.Count(usr => usr.active);
double average = (double)((double)numActive / (double)collection.content.Count);
return average;
}
And my controller:
public class UserController : AsyncController
{
// GET: User
public async Task<ActionResult> Index()
{
// I get the exception on here
double user = await Reports.General_Classes.User.GetActiveUsers();
return View(user);
}
}
My stack trace is:
[WebException: The remote name could not be resolved: '...']
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) +606
System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) +64
[HttpRequestException: An error occurred while sending the request.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
Reports.General_Classes.<GetActiveUsers>d__36.MoveNext() in ...\User.cs:49
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Report_Retriever.Controllers.<Index>d__0.MoveNext() in ...\UserController.cs:17
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
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() +48
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) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
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) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
And here's the working code from my DLL and unit test:
[TestMethod]
public async Task GetActiveUserTests()
{
double percent = await User.GetActiveUsers();
Assert.IsTrue(percent >= 0 && percent <= 1);
}
And here's the GetActiveUsers method from my console application DLL (which is essentially identical to the method I'm using above):
public static async Task<double> GetActiveUsers()
{
string json;
using (var client = UtilityMethods.GetHttpClient(false))
{
HttpResponseMessage message = await client.GetAsync("users");
json = await message.Content.ReadAsStringAsync();
}
UserCollection collection = JsonConvert.DeserializeObject<UserCollection>(json);
int numActive = collection.content.Count(usr => usr.active);
double average = (double)((double)numActive / (double)collection.content.Count);
return average;
}
As part of my research, I read the following Stack Overflow posts:
ASP.NET Exception: The remote name could not be resolved: 'apiconnector.com'
System.Net.WebException: The remote name could not be resolved:
In both of those cases, they could access the remote location from a browser but not programmatically. My case is somewhat different, though: I can perform calls against the API from a unit test, but not from an ASP.NET MVC application.
In this post, the original poster was able to access this locally but not from a server. Again, though, this doesn't exactly apply to my case because both are running locally within Visual Studio.
The result is the same no matter how many times I run them - i.e. the unit test always passes and the ASP.NET MVC call always fails.
My question, then, is why does the code work in a unit test but virtually identical code fails in ASP.NET MVC?

IndexOutOfRangeException and NullReferenceException in MVC 5 Controller

For the project I am working on we use a controller called "MediaDepot". This controller handles all requests for files on the server such as images.
The datamodel checks if the user has access to the file via the session object. The controller gets the session as a readonly dictionary.
Below a sample of our controller:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MediaDepotController : AsyncController
{
[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client, Duration = 10, VaryByParam = "Hash;Width;Height;ImageID")]
public ActionResult Get(string Hash, int Width, int Height, int ImageID)
{
ActualRequest aRequest = new ActualRequest(Request, Response as HttpResponseWrapper, ControllerContext, HttpContext, Session);
MediaDepotResult result = MediaDepot.MediaDepot.Instance.GetFilePathOfImageItem(aRequest, Hash, Width, Height, ImageID);
var File = Server.MapPath(result.FilePath);
return base.File(File, result.FileType);
}
On the production server the session object will sometimes refuse to load throwing out IndexOutOfRangeException or NullReferenceException on all requests from the client with that session.
Stack trace
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.Collections.ArrayList.Add(Object value) +38
System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value) +98
System.Collections.Specialized.NameObjectCollectionBase.BaseSet(String name, Object value) +43
System.Web.SessionState.SessionStateItemCollection.set_Item(String name, Object value) +29
System.Web.SessionState.HttpSessionStateContainer.set_Item(String name, Object value) +14
System.Web.HttpSessionStateWrapper.set_Item(String name, Object value) +17
System.Web.Mvc.SessionStateTempDataProvider.SaveTempData(ControllerContext controllerContext, IDictionary2 values) +101
System.Web.Mvc.TempDataDictionary.Save(ControllerContext controllerContext, ITempDataProvider tempDataProvider) +102
System.Web.Mvc.Controller.PossiblySaveTempData() +72
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +69
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.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() +9651516
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I know this is a concurrency issue with the session object in mvc but how can it be prevented? And is there a better solution to serve files to the end user without linking to the files directly?

Getting "A task was cancelled" while trying to create a document in DocumentDB [duplicate]

This question already has answers here:
Want to understand async
(3 answers)
Closed 2 years ago.
When I try to create a document in my DocumentDB database using the following code, the code hangs where I call CreateDocumentAsync() and eventually gives me "A task was cancelled" error.
Any idea why?
public static async Task<Employee> CreateEmployee(Employee emp)
{
try
{
using (client = new DocumentClient(new Uri(endPointUrl), authorizationKey))
{
//Get the database
var database = await GetDatabaseAsync();
//Get the Document Collection
var collection = await GetCollectionAsync(database.SelfLink, "Employees");
await client.CreateDocumentAsync(collection.SelfLink, emp);
// Do something else with employee
}
}
catch
{
// Handle error
}
return emp;
}
P.S. For brevity, I didn't include the code for GetDatabaseAsync() and GetCollectionsAsync() sections. Please note that the employee document IS created in my database. So, this code clearly connects to the DocumentDB database, finds the collection and creates the document.
Just not sure why it hangs and eventually returns the error.
***** Update ******
Here's the error details:
A task was canceled.
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.Threading.Tasks.TaskCanceledException: A task was canceled.
Source Error:
HttpResponseMessage response = await client.PostAsJsonAsync("api/hr/register", employee);
Stack Trace:
[TaskCanceledException: A task was canceled.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +10915395
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
ConsumerWebApi.Controllers.<Index>d__0.MoveNext() in c:\Users\Sam\Documents\Visual Studio 2013\Projects\ConsumerWebApi\ConsumerWebApi\Controllers\HomeController.cs:36
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +10915367
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +135
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +135
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +132
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +138
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
I had a similar error thrown using one of DocumentClients async functions. I used await correctly for each call but then I found that this was caused by a proxy server interfering with the traffic. So for those working from inside a company network - consider checking this.
Just try client.
Timeout = TimeSpan.FromSeconds(240);

Categories