I got strange exception in mongodb.I wrote a simple service into vs and worked well till last night. but now when I am running my service by VS I get this exception:
An exception of type 'System.TimeoutException' occurred in MongoDB.Driver.Core.dll but was not handled in user code
Additional information: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode = Primary, TagSets = [] } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "127.0.0.1:27017" }", EndPoint: "127.0.0.1:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:27017
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.TcpStreamFactory.<ConnectAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.TcpStreamFactory.<CreateStreamAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__47.MoveNext()
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at MongoDB.Driver.Core.Servers.ClusterableServer.<HeartbeatAsync>d__42.MoveNext()" }] }.
why I got this exception and how could I handle it?
why my service worked well before?
this is where I got this exception:
public static IList<Location> GetFinalLocationsInTopicInLocationTable(string topic)
{
logger.Trace(Constants.LOG_MESSAGE_METHOD_STARTED);
var collection = GetDbMongo().GetCollection<Location>(DB_COLLECTION_LOCATIONS);
var matchFilter = Builders<Location>.Filter.Regex("Topic", topic);
var groupFilter = new BsonDocument { { "_id", "$DeviceId" }, { "max", new BsonDocument("$max", "$CreationDateTime") } };
var location = collection
.Aggregate()
.Match(matchFilter)
.Group(groupFilter)
.ToList(); // -----I got this exception
I resolve that. my problem was:
my mongodb service was stopped. I do not know why it was stopped but when I start it, the problem gone.
Related
So I wrote a little c# utility which connects to my devops azure repo and downloads a bunch of files in a zip, then unpacks the zip file(s) and then does a text search and replace to customise the files.
This utility was working fine up to Friday 8th. On Monday 11th the utility started telling me i was unauthorised.
This utility is used by 3 other colleagues and it is still working a-ok for them, just not me :(
The utility has been working fine for over 4 months until his week.
Here's the pertinent code:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using System.IO;
using System.IO.Compression;
namespace ########.######.####.#######
{
class Program
{
const String c_collectionUri = "https://dev.azure.com/#################";
const String c_projectName = "########.######.#######.######.#########";
const String c_variableGroupId = "########-####-####-####-############"; // id for the LIVE project / repos
const String download_dir = #"C:\###########\";
const String dev_short_name_txt = "$$dev_shortname$$";
const String dev_long_name_txt = "$$dev_long_name$$";
const String todays_date_txt = "$$todays_date$$";
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
private static string dev_short_name;
private static string dev_long_name;
private static string todays_date;
static void Main(string[] args)
{
// gets just the username, e.g. ############
dev_short_name = Environment.UserName;
Console.WriteLine("Who are you : " + dev_short_name);
DateTime today = DateTime.Today; // As DateTime
todays_date = today.ToString("dd/MM/yyyy"); // As String
Console.WriteLine("Today is : " + todays_date);
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
Console.WriteLine("");
Console.WriteLine("Projects....");
Console.WriteLine("");
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamHttpClient teamClient = connection.GetClient<TeamHttpClient>();
// Call to get the list of projects
IEnumerable<TeamProjectReference> projects = projectClient.GetProjects().Result;
Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>> results = new Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>>();
// Iterate over the returned projects
foreach (var project in projects)
{
// Get the teams for the project
IEnumerable<WebApiTeam> teams = teamClient.GetTeamsAsync(project.Name).Result;
// Add the project/teams item to the results dictionary
results.Add(project, teams);
Console.WriteLine(" " + project.Id + " " + project.Name);
Here's the error output:
Who are you : ###############
Today is : 14/07/2022
Projects....
Unhandled Exception: Microsoft.VisualStudio.Services.WebApi.VssServiceResponseException: Unauthorized
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<HandleResponseAsync>d__53.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__47`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.Location.Client.LocationHttpClient.<GetConnectionDataAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<GetConnectionDataAsync>d__56.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<ConnectAsync>d__41.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<EnsureConnectedAsync>d__39.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<CheckForServerUpdatesAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<FindServiceDefinitionAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<LocationForCurrentConnectionAsync>d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.LocationService.<ResolveLocationDataAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.LocationService.<GetLocationDataAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientInstanceAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientServiceImplAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientAsync>d__14`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.TaskExtensions.SyncResult[T](Task`1 task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.GetClient[T]()
at ########.######.####.#######.Program.Main(String[] args) in C:\########\########.######.####.#######\########.######.####.#######\Program.cs:line 60
I've googled around and tried various things like:
deleting C:\Users\###########\AppData\Local.IdentityService
clearing temp internet files / folders from both Edge and Chrome
removing all generic credetials from the Credential Manager
using alternatives to VssCredentials / VssClientCredentialStorage / VssConnection like:
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
Console.WriteLine("creds : " + creds.Windows.ToString());
Console.WriteLine("creds2 : " + creds.Storage.ToString());
// Connect to Azure DevOps Services
VssConnection connection;
ProjectHttpClient projectClient;
try
{
connection = new VssConnection(new Uri(c_collectionUri), creds);
projectClient = connection.GetClient<ProjectHttpClient>();
}
catch (VssServiceResponseException e)
{
Console.WriteLine(e);
connection = new VssConnection(new Uri(c_collectionUri), new VssAadCredential());
//connection = new VssConnection(new Uri(c_collectionUri), new VssBasicCredential(string.Empty, personalAccessToken));
//connection = new VssConnection(new Uri(c_collectionUri), new VssBasicCredential("##############","###################################"));
projectClient = connection.GetClient<ProjectHttpClient>();
}
//VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
//VssConnection connection = new VssConnection(new Uri(c_collectionUri), new VssAadCredential());
But I still can't get in!!!
I'm not aware of any changes being made to my device.
Our IT guys fixed this one. I was missing a trusted site setting, which they've added via a browser GPO for edge / chrome.
:)
I am working on Google Sheet Api, the below attached code is working fine in development environment. After deploying website in IIS, I am phasing the belwo error. I am working with ASP.NET MVC Environment.
System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=131872634482-gh84b1avui5t9f5ugfv667eiotkivu1p.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A56626%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
at EmailDashboard.Extensions.SpreadsheetV4Extensions.GetService() in D:\Project\EmailDashboard\SourceCodeWeb\EmailDashboard\Extensions\SpreadsheetV4Extensions.cs:line 43
---> (Inner Exception #0) System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=131872634482-gh84b1avui5t9f5ugfv667eiotkivu1p.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A56626%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext()<---
public SheetsService GetService()
{
try
{
string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/client_Secret_Sheet.json");
UserCredential credential = null;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
string folderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Credentials/");
if (folderPath != null)
{
string filePath = Path.Combine(folderPath, "SpreadsheetCredentials");
if (Directory.Exists(filePath))
{
var directoryInfo = new DirectoryInfo(filePath);
//foreach (FileInfo file in directoryInfo.GetFiles()) {
// file.Delete();
//}
//foreach (DirectoryInfo dir in directoryInfo.GetDirectories()) {
// dir.Delete(true);
//}
}
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { SheetsService.Scope.Spreadsheets },
Environment.UserName,
CancellationToken.None,
new FileDataStore(filePath, true)).Result;
}
}
// Create Drive API service.
SheetsService service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = _applicationName,
});
return service;
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
So looking at your code you are trying to make an authorized client by doing:
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { SheetsService.Scope.Spreadsheets },
Environment.UserName,
CancellationToken.None,
new FileDataStore(filePath, true)).Result;
This is advised for doing installed apps in your PC. For deploying this in a server you would need to change your code.
All the process and option you have is very detailed in this page. Basically Google has a package to implement the authentication in MVC.
Reference
NuGet Package for Google.Apis.Auth.Mvc
Github Library for Google C# API
I have below code which causing issue while fetching data
var result = client.GetAsync(requestUri).Result;
If I hit requestUri from browser then it works fine. but from above code it gives below error.
Error :
One or more errors occurred.An error occurred while sending the request.The underlying connection was closed: An unexpected error occurred on a send.Authentication failed because the remote party has closed the transport stream.
Stack Trace1 :
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at foo(String resultUrl)
at dooo(String param, String resultUrl)
at foo.<>c__DisplayClass2.<Product>b__0(String x, String y)
at foo[T](Func3 fn) at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
Stack Trace2
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at Foo1(String resultUrl)
at Foo2(String param, String resultUrl)
at Foo3.<>c__DisplayClass2.<Product>b__0(String x, String y)
at Foo4(Func3 fn) at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()
Also i tried awaitable call but no luck. Can we increase request timeout for get request in this scenario.
Awaitable code I tried
var result = await client.GetAsync(requestUri);
if (!result.IsSuccessStatusCode) throw new Exception(string.Format("Unable to receive data from Uri: {0}", uri.ToString()));
// write the results
using (var write = File.Create(filePath))
using (var read = await result.Content.ReadAsStreamAsync())
{
read.Seek(0, SeekOrigin.Begin);
read.CopyTo(write);
}
If the response is talking long time and you want to increase the timeout just set it on the client: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout(v=vs.118).aspx
Also from looking at the class itself:
TimeSpan defaultTimeout = TimeSpan.FromSeconds(100.0);
TimeSpan maxTimeout = TimeSpan.FromMilliseconds((double) int.MaxValue);
TimeSpan infiniteTimeout = TimeSpan.FromMilliseconds(-1.0);
I am trying to figure out how to properly handle some exceptions in a Task:
Calling Method:
Task<Branch3GInfo> getActive3GRoutersTask =
Task.Run(
() => CAS.Service.GetBranch3GInformationAsync(3)
);
try
{
Task.WaitAll(discoverRouterExtendedInfoTask, getActive3GRoutersTask);
}
catch(AggregateException aggEx)
{
StringBuilder sb = new StringBuilder();
sb.Append("Some problems occured on GetNodesInCriticalCondition(): \n");
foreach (var ex in aggEx.InnerExceptions)
{
sb.Append(ex.Message);
}
Trace.TraceError(sb.ToString());
}
var branch3gInfo = getActive3GRoutersTask.Result;
var branch3gInfo = getActive3GRoutersTask.Result; throws a System.Aggregate Exception.
Called method:
public async Task<Branch3GInfo> GetBranch3GInformationAsync(int searchDepth)
{
var branch3gInfo = await GetBranch3GInterfacesAsync();
var activeRoutersExtInfos = new List<CasApiRouterModelExtendedInfo>();
foreach (var netInterface in branch3gInfo.Branch3GActiveInterfaces)
{
try
{
var task = GetRouterExtendedInfoFromInterfaceAsync(netInterface, searchDepth);
var result = await task;
if (task.Status == TaskStatus.RanToCompletion && result != null)
{
activeRoutersExtInfos.Add(result);
}
else
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName + ".");
}
}
catch (Exception ex)
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName +
": \n" + ex.Message);
}
}
return new Branch3GInfo()
{
Branch3GActiveInterfaces = branch3gInfo.Branch3GActiveInterfaces,
Branch3GCapableInterfaces = branch3gInfo.Branch3GCapableInterfaces,
Branch3GActiveRouters = activeRoutersExtInfos.ToArray()
};
}
From my code, I am making the assumption that GetBranch3GInformationAsync() should be either executing the else clause which doesn't add the result to activeRoutersExtInfos, OR, it should be catching the exception. Why is it that the calling method throws a System.AggregateException if I am handling this in GetBranch3GInformationAsync()?
How do I go about fixing this so that any call to GetRouterExtendedInfoFromInterfaceAsync() that fails due to an exception is ignored, and so that it doesn't break my code?
UPDATE:
Stack trace for the InnerException in System.AggregateException ("The remote server returned an error: (500) Internal Server Error.")
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.CasApiRestCall.<ExecuteAsync>d__38.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Queries\CasApiRestCall.cs:line 294
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<RenderAndExecuteRestCallAsync>d__103.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 2516
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<QueryModelsFilterByAttributeNotDeviceOnlyAsync>d__51.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 1196
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 442
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInformationAsync>d__26.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 246
You can see from your call stack:
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext()
that it is the call to GetBranch3GInterfacesAsync that is failing, not the call to GetRouterExtendedInfoFromInterfaceAsync. GetBranch3GInterfacesAsync is called outside the try block, so naturally the exception will propagate.
I get this exception intermittently in my asp.net mvc 5 c# web application:
Server cannot append header after HTTP headers have been sent.
It just happens uploading images to S3 method (Web Api Controller).
The presendrequestheaders in Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null &&
app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
The method that trigger the error:
[HttpPost]
[Route("UploadImageJSON")]
public IHttpActionResult UploadImageJSON(HttpRequestMessage request)
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count != 1) return BadRequest();
var postedFile = httpRequest.Files[0];
var contentType = postedFile.ContentType;
if (!contentType.Contains("image"))
{
return StatusCode(HttpStatusCode.NotAcceptable);
}
var keyUploadFiles = Constants.UrlS3Amazon +
S3.UploadToS3WithStream(postedFile.InputStream, contentType);
return Json(JsonConvert.SerializeObject(keyUploadFiles));
}
EDIT: More information... I have my Web App hosted in Elastic BeanStalk with a load balancer, the load balancer has installed a SSL Certificate, and the connection between the load balancer and the EC2 instances are in ports 80. Maybe it could be helpful.
The Elmah log:
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary2 headers, String key, String[] values)
at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware1.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Mapping.MapMiddleware.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thanks!!
have you tried with removing app.Context.Response.Headers.Remove("Server"); i think there is this is the issue?