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.
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.
:)
Note: This runs without any issues on my local computer, but when I push it up to our Azure instance I see the TimeoutExpired
I'm running into a weird issue where we are inserting records into the database. The file I'm working on has 103k inserts. The actual inserts to the database are completed successfully. When it goes to update my database table via EF Core that the import has been successful I see this error:
Error: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__180_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- 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 Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>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.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.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.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`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.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__81.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.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__79.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.EntityFrameworkCore.DbContext.<SaveChangesAsync>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 PTI.BI.API.ExcelImporter.DAL.Repositories.BaseRepository.<SaveChangesAsync>d__13.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 PTI.BI.API.ExcelImporter.DAL.Repositories.ImportRepository.<UpdateImportGenerateScript>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 PTI.BI.API.ExcelImporter.BLL.Service.ImportService.<UpdateImportGenerateScript>d__31.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 PTI.BI.API.ExcelImporter.BLL.Service.ImportService.<ProcessImport>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
Here is the code that is doing the updates to my database, one at a time (for error checking). This code is working fine.
using (var sqlConnection = new SqlConnection(connectionString))
{
try
{
sqlConnection.Open();
sqlTransaction = sqlConnection.BeginTransaction();
// #### Pre populate items (generate delete statement)
trackingInfo.FileDetail = UpdateImportMetricStatus(trackingInfo.FileDetail, ImportMetricStatus.PrepopulateScript);
trackingInfo = await PrepopulateApplyScript(trackingInfo).ConfigureAwait(false);
if (trackingInfo.IsSuccessful == false)
{
return trackingInfo;
}
// apply the delete records sql script if found.
if (string.IsNullOrWhiteSpace(trackingInfo.DeleteRecordsSqlScript.ToString()) == false)
{
trackingInfo.FileDetail = UpdateImportMetricStatus(trackingInfo.FileDetail, ImportMetricStatus.GenerateDeleteSqlScript);
errorSqlScript = trackingInfo.DeleteRecordsSqlScript.ToString();
using (var cmd = new SqlCommand(trackingInfo.DeleteRecordsSqlScript.ToString(), sqlConnection, sqlTransaction))
{
cmd.CommandType = CommandType.Text;
await cmd.ExecuteScalarAsync().ConfigureAwait(false);
}
// append delete statement to the main SQL script
trackingInfo.SqlScript.AppendLine(trackingInfo.DeleteRecordsSqlScript.ToString());
}
// #### Create table script IF we are creating a new table
if (trackingInfo.FileDetail.DestinationDetail.CreateNewTable == true && trackingInfo.FileDetail.DestinationDetail.UseExistingTable == false)
{
trackingInfo = await CreateTableScript(trackingInfo).ConfigureAwait(false);
if (trackingInfo.IsSuccessful == false)
{
return trackingInfo;
}
// apply the create table sql script if found.
if (string.IsNullOrWhiteSpace(trackingInfo.CreateTableSqlScript.ToString()) == false)
{
trackingInfo.FileDetail = UpdateImportMetricStatus(trackingInfo.FileDetail, ImportMetricStatus.GenerateCreateTableScript);
errorSqlScript = trackingInfo.CreateTableSqlScript.ToString();
using (var cmd = new SqlCommand(trackingInfo.CreateTableSqlScript.ToString(), sqlConnection, sqlTransaction))
{
cmd.CommandType = CommandType.Text;
await cmd.ExecuteScalarAsync().ConfigureAwait(false);
}
// append delete statement to the main SQL script
trackingInfo.SqlScript.AppendLine(trackingInfo.CreateTableSqlScript.ToString());
}
}
// ### Insert table scripts
trackingInfo.FileDetail = UpdateImportMetricStatus(trackingInfo.FileDetail, ImportMetricStatus.GenerateInsertScripts);
trackingInfo = await GenerateInsertTableScript(trackingInfo).ConfigureAwait(false);
// apply the create table sql script if found.
if (string.IsNullOrWhiteSpace(trackingInfo.InsertSqlScript.ToString()) == false)
{
trackingInfo.FileDetail = UpdateImportMetricStatus(trackingInfo.FileDetail, ImportMetricStatus.PopulatingInsertScripts);
foreach (var item in trackingInfo.InsertSqlScript)
{
errorSqlScript = item;
using (var cmd = new SqlCommand(item, sqlConnection, sqlTransaction))
{
cmd.CommandType = CommandType.Text;
await cmd.ExecuteScalarAsync().ConfigureAwait(false);
}
currentRowLine++;
// append insert statements to the main script...
trackingInfo.SqlScript.AppendLine(item).AppendLine();
}
}
if (trackingInfo.IsSuccessful == false)
{
return trackingInfo;
}
if (trackingInfo.IsSuccessful == true)
{
sqlTransaction.Commit();
return trackingInfo;
}
else
{
return trackingInfo;
}
}
catch (Exception ex)
{
sqlTransaction.Rollback();
trackingInfo.IsSuccessful = false;
trackingInfo.ImportMetricUpdateError = new ImportMetricUpdateErrorDTO(trackingInfo.ImportMetricId)
{
ErrorLineNbr = currentRowLine + 1, // add one to match up with the excel file
ErrorMessage = string.Format(CultureInfo.CurrentCulture, "{0}", ex.Message),
ErrorSQL = errorSqlScript,
RowsProcessed = currentRowLine
};
await LogImporterError(trackingInfo.FileDetail, ex.ToString()).ConfigureAwait(false);
return trackingInfo;
}
}
Again, the delete, create, insert statements all work and update my SQL database without any issues.
Then here is where my code fails:
public async Task UpdateImportMetric(ImportMetricUpdateDTO importMetricUpdate)
{
if (importMetricUpdate == null)
{
throw new ArgumentNullException(nameof(importMetricUpdate));
}
var importMetricDbRecord = await ImportContext.ImportMetrics
.Where(x => x.ImportMetricId == importMetricUpdate.ImportMetricId)
.FirstOrDefaultAsync().ConfigureAwait(false);
if (importMetricDbRecord == null)
{
throw new RecordNotFoundException("No import metric with id: " + importMetricUpdate.ImportMetricId + " could be found.");
}
importMetricDbRecord.ImportStatus = importMetricUpdate.ImportStatus;
importMetricDbRecord.ImportStatusHistoriesJson = string.IsNullOrWhiteSpace(importMetricUpdate.ImportStatusHistoriesJson) == true ? importMetricDbRecord.ImportStatusHistoriesJson : importMetricUpdate.ImportStatusHistoriesJson;
importMetricDbRecord.Ended = importMetricUpdate.Ended;
importMetricDbRecord.Duration = importMetricUpdate.Duration;
importMetricDbRecord.RowsProcessed = importMetricUpdate.RowsProcessed;
importMetricDbRecord.IsSuccessful = importMetricUpdate.IsSuccessful;
importMetricDbRecord.ErrorLineNbr = importMetricUpdate.ErrorLineNbr;
importMetricDbRecord.ErrorMessage = importMetricUpdate.ErrorMessage;
importMetricDbRecord.ErrorSQL = importMetricUpdate.ErrorSQL;
importMetricDbRecord.ModifiedBy = ImportContext.UserRequestingId;
importMetricDbRecord.ModifiedDate = DateTime.UtcNow;
await SaveChangesAsync().ConfigureAwait(false);
}
As you can see the issue appears to be on my SaveChangesAsync().
So I think it is something with EF Core instead of the code to actually insert the statements into the db since that appears to be working.
Also, after starting the Import from the user clicking a button on the MVC page, I am kicking off the Import in Async mode, so the UI responds back and a loading panel will run for the user.
Here is that code:
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(async ()=> await ProcessImport(submitImportItemsAndProcessImport.ImportDetailId, importMetricId, currentUserId));
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
I'm in a using() on the connection so that should be closed out.
It is almost like something is being left open and therefore EF Core can't continue with the updates after moving away from using SQLCommand.
Any ideas?
Answer:
It appears the script is so large that StringBuilder.ToString(); was causing an Out of Memory exception and thus causing the timeout.
Since the script is so large. We are planning to go to FileStream instead of StringBuilder.
Google.Apis.Http.Configurable MessageHandler.d__59.MoveNext() --- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 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
System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Auth.OAuth2.Requests.TokenRequestExtenstions.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---
It is working fine with one server but not working with another server
private static async Task<string> GetAccessToken()
{
//var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string token = string.Empty;
try
{
List<string> scope = new List<string>();
scope.Add(firebaseMessagingURL); //Will Not Change --Until or unless changes by google
GoogleCredential googlCredentail = GoogleCredential.FromJson(firebasecredential).CreateScoped(scope);
token = await googlCredentail.UnderlyingCredential.GetAccessTokenForRequestAsync();
return token;
}
catch (Exception ex)
{
Logging.WriteLog(ex, Logging.LogMsgType.General, Logging.CacheStoresName.Empty.ToString());
}
return token;
}
I've been doing a bot with the Microsoft Bot Framework in C# and I encountered a problem.
The problem is that when I call "PromptDialog" to get a String from the user, in this case a password, it doesn't ask for it, it opens the "Password" method and crashes when trying to obtain that String.
Thanks for your help!
The class extends LUISDialog
PromptDialog.Text(context, resume: Password, prompt: "Enter password:");
LUIS Intent null:
[LuisIntent("")]
public async Task None(IDialogContext context, IAwaitable<IMessageActivity> activity, LuisResult result)
{
Boolean PassLogin;
Start(context, activity); //Does this need to be awaited?
if (!context.UserData.TryGetValue<Boolean>("PassLogin", out PassLogin)) PassLogin = false;
if (PassLogin)
{
var act = await activity;
if (act.Conversation.IsGroup != null && act.Conversation.IsGroup.Value)
{
context.Wait(MessageReceived);
}
else
{
await Nothing(context, activity, result);
}
}
else context.Wait(MessageReceived);
}
Start Method. The Start method is called by every intent from LUIS.
public async Task Start(IDialogContext context, IAwaitable<IMessageActivity> activity)
{
Boolean PassLogin, start;
if (!context.UserData.TryGetValue<Boolean>("PassLogin", out PassLogin))
{
PassLogin = false;
context.UserData.SetValue<Boolean>("PassLogin", PassLogin);
}
if (!context.UserData.TryGetValue<Boolean>("start", out start))
{
start = true;
}
if (start)
{
PromptDialog.Text(context, resume: Password, prompt: "Enter password:");
await context.PostAsync("Something"); //This prints out before going to password.
}
await GetKey(context, activity);
}
private async Task Password(IDialogContext context, IAwaitable<String> argument)
{
var response = await argument;
if (response=="test")
{
context.UserData.SetValue<Boolean>("PassLogin", true);
await context.PostAsync("Correct Password.");
if (context.UserData.Get<Boolean>("PassLogin"))
{
await context.PostAsync("Welcome");
context.UserData.SetValue<Boolean>("start", false);
}
}
else
{
context.UserData.SetValue<Boolean>("PassLogin", false);
await context.PostAsync("Incorrect password.");
}
context.Wait(MessageReceived); //Does this need to be here? (Tried with and without.)
}
This is what the error says:
Exception: Microsoft.Bot.Builder.Internals.Fibers.InvalidNextException: invalid next: Wait: Poll Object for ThunkStart.Rest have Object at Microsoft.Bot.Builder.Internals.Fibers.Fiber1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult() at Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog1.<ResumeAsync>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.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.<Rest>d4.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.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d19.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.Bot.Builder.Internals.Fibers.Frame1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>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 Microsoft.Bot.Builder.Internals.Fibers.Fiber1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d13.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.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IDialogStack-PollAsync>d19.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.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d21`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.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d31.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.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21.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.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d21.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.Bot.Builder.Dialogs.Internals.ScoringDialogTask1.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d31.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.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.MoveNext() — End of stack trace from previous location where exception was thrown — at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d3`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.Bot.Builder.Dialogs.Internals.SerializingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d41.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.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__51.MoveNext()
As I wrote in the comments, there are a few issues that would have to be solved:
The call to the Start method must be awaited
There shouldn't be code after the call to PromptDialog.Text. That code is starting a new dialog that will continue in the ResumeAfter method once it's done
All the code after the Start call seems to depend on the ResumeAfter of the Prompt so it should be moved there.
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);