I recently went through Confluent Kafka library in C# .net 4.7.2 framework version. But, many times I faced Local Value serialization error. Is this error is a generic one? or this error tells anything specifically? I'm not sure when will this error raises?
var rs = (RecordSchema)RecordSchema.Parse(#"{
""namespace"": ""Confluent.Kafka.Examples.AvroSpecific"",
""type"": ""record"",
""name"": ""ProduceConsumeUser2"",
""fields"": [
{""name"": ""name"", ""type"": ""string""},
{""name"": ""favorite_number"", ""type"": [""int"", ""null""]},
{""name"": ""favorite_color"", ""type"": [""string"", ""null""]}
]}");
using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig)){
using (var genericProducer = new ProducerBuilder<string, GenericRecord>(producerConfig)
.SetValueSerializer(new AvroSerializer<GenericRecord>(schemaRegistry).AsSyncOverAsync())
.Build())
{
var genericRecord = new GenericRecord(rs);
genericRecord.Add("name", "my name 2");
genericRecord.Add("favorite_number", 44);
genericRecord.Add("favorite_color", null);
var message = new Message<string, GenericRecord>
{
Key = contentEventName,
Value = genericRecord
};
Task.Run(() => genericProducer.ProduceAsync(contentEventName, message)).ConfigureAwait(false).GetAwaiter().GetResult();
}}
Error we get:
"Error":{
"Code":-161,
"IsFatal":false,
"Reason":"Local: Value serialization error",
"IsError":true,
"IsLocalError":true,
"IsBrokerError":false
},
"Message":"Local: Value serialization error",
"Data":{ },
"InnerException":{
"ClassName":"System.Threading.Tasks.TaskCanceledException",
"Message":"A task was canceled.",
"Data":null,
"InnerException":null,
"HelpURL":null,
"StackTraceString":" at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<ExecuteOnOneInstanceAsync>d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<RequestAsync>d__10`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<RegisterSchemaAsync>d__18.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.CachedSchemaRegistryClient.<RegisterSchemaAsync>d__21.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.Serdes.GenericSerializerImpl.<Serialize>d__8.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.Serdes.AvroSerializer`1.<SerializeAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\r\n at Confluent.Kafka.Producer`2.<ProduceAsync>d__52.MoveNext()",
"RemoteStackTraceString":null,
"RemoteStackIndex":0,
"ExceptionMethod":"8\nThrowForNonSuccess\nmscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Runtime.CompilerServices.TaskAwaiter\nVoid ThrowForNonSuccess(System.Threading.Tasks.Task)",
"HResult":-2146233029,
"Source":"mscorlib",
"WatsonBuckets":null
},
"StackTrace":" at Confluent.Kafka.Producer`2.<ProduceAsync>d__52.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\r\n at LogEvent(String contentEventName, IDictionary`2 e, RecordSchemaName re)",
"HelpLink":null,
"Source":"Confluent.Kafka",
"HResult":-2146233088
I cannot be for certain. But I got to this page because I had the same exception details /issue...
For me, solving the issue was making sure I had the correct credentials for the Schema Registry. DOH! Hope this helps for at least someone else!
In my C# test using the Confulent.Kafka and Confluent.SchemaRegistry the (username:password) are that exact syntax with the (:) colon in one string
string credentials ="MyUserName:mypassword";
var schemaRegistryConfig = new SchemaRegistryConfig()
{
Url = config.GetValue<string>("ConfluentCloud:SchemaRegistry:Url", string.Empty),
BasicAuthUserInfo = config.GetValue<string>("ConfluentCloud:SchemaRegistry:Credentials", string.Empty),
};
// no serializer required for string key
using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig))
... etc. etc.
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 keep getting the error System.Threading.Tasks.TaskCanceledException: A task was canceled when trying to any user admin operation on Firebase, using C# SDK.
Here is an example of how I am doing the call to Firebase Admin:
public static async Task<bool> SaveUserInFirebaseAsync(string email, string nome, bool emailVerified, string password, Guid uid)
{
UserRecordArgs args = new UserRecordArgs()
{
Uid = uid.ToString().ToUpper(),
Email = email,
EmailVerified = emailVerified,
DisplayName = nome,
Password = password
};
try
{
UserRecord userRecord = await FirebaseAuth.DefaultInstance.CreateUserAsync(args);
}
catch (Exception ex)
{
Logging.startFileLog(ex.ToString(), null, null, null, LogType.Error);
return false;
}
return true;
}
I dont know if its a firebase error or if I am doing the async call wrong.
Edit:
Here is the full stack trace
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Google.Apis.Http.ConfigurableMessageHandler.<SendAsync>d__59.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.Net.Http.HttpClient.<FinishSendAsyncBuffered>d__58.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 FirebaseAdmin.Util.ErrorHandlingHttpClient`1.<SendAsync>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 FirebaseAdmin.Util.ErrorHandlingHttpClient`1.<SendAndReadAsync>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 FirebaseAdmin.Util.ErrorHandlingHttpClient`1.<SendAndDeserializeAsync>d__7`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 FirebaseAdmin.Auth.Users.FirebaseUserManager.<PostAndDeserializeAsync>d__29`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 FirebaseAdmin.Auth.Users.FirebaseUserManager.<GetUserAsync>d__28.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 FirebaseAdmin.Auth.Users.FirebaseUserManager.<GetUserByEmailAsync>d__15.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 FirebaseAdmin.Auth.AbstractFirebaseAuth.<GetUserByEmailAsync>d__28.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 FirebaseAdmin.Auth.AbstractFirebaseAuth.<GetUserByEmailAsync>d__27.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 TeltonikaSiteWebApplication.WebApplicationHelpers.FireBaseHelper.<SaveUserInFirebaseAsync>d__5.MoveNext()
I created a bot with Microsoft Botframework C# SDK V4 and it is working well. Now I want to add some images to that bot. I am using cards but cards are taking only url of an image. I want to send the images which are in my local folder. How can I make it work??
I already tried this with 15.handling attachments github repo(https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/15.handling-attachments). And while I am using the exact code in handling attachments github repo, I am getting the below exception stacktrace for inline attachments.
Sorry, it looks like something went wrong.’ at Microsoft.Bot.Connector.Conversations.d__10.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 Microsoft.Bot.Connector.ConversationsExtensions.d__17.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 Microsoft.Bot.Builder.BotFrameworkAdapter.d__15.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 Microsoft.Bot.Builder.TurnContext.<>c__DisplayClass22_0.
<g__SendActivitiesThroughAdapter|1>d.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 Microsoft.Bot.Builder.TurnContext.d__21.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 Microsoft.BotBuilderSamples.AttachmentsBot.d__0.MoveNext() in
C:\botbuilder-samples\samples\csharp_dotnetcore\15.handling-attachments\AttachmentsBot.cs:line 65
— 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 Microsoft.Bot.Builder.MiddlewareSet.d__3.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 Microsoft.Bot.Builder.BotAdapter.d__13.MoveNext()’
How can I resolve this issue??
The 15.handling-attachments sample demonstrates how to read a local file, and attach it as a base64 encoded image:
reply.Attachments = new List<Attachment>() { GetInlineAttachment() };
private static Attachment GetInlineAttachment()
{
var imagePath = Path.Combine(Environment.CurrentDirectory, #"Resources\architecture-resize.png");
var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));
return new Attachment
{
Name = #"Resources\architecture-resize.png",
ContentType = "image/png",
ContentUrl = $"data:image/png;base64,{imageData}",
};
}
Another option is to use the ConnectorClient's UploadAttachmentAsync api:
private async Task SendFile(ITurnContext turnContext)
{
var webRoot = _env.ContentRootPath;
var imagePath = System.IO.Path.Combine(webRoot, "Resources", "BotFrameworkDiagram.png");
var connector = turnContext.TurnState.GetValueOrDefault("Microsoft.Bot.Connector.IConnectorClient") as ConnectorClient;
var attachments = new Attachments(connector);
var response = await attachments.Client.Conversations.UploadAttachmentAsync(
turnContext.Activity.Conversation.Id,
new AttachmentData
{
Name = "BotFrameworkDiagram.png",
OriginalBase64 = File.ReadAllBytes(imagePath),
Type = "image/png"
});
var attachmentUri = attachments.GetAttachmentUri(response.Id);
var attachment = new Attachment
{
Name = "BotFrameworkDiagram.png",
ContentType = "image/png",
ContentUrl = attachmentUri
};
var reply = turnContext.Activity.CreateReply();
reply.Attachments.Add(attachment);
await turnContext.SendActivityAsync(reply);
}
I am trying to forward request from one API to another one like this:
protected Task<HttpResponseMessage> ForwardRequestToSomeApi()
{
string forwardUri = "https://some.api" + Request.RequestUri.PathAndQuery;
Request.Headers.Remove("Host");
Request.RequestUri = new Uri(forwardUri);
if (Request.Method == HttpMethod.Get)
{
Request.Content = null;
}
return new HttpClient().SendAsync(Request, HttpCompletionOption.ResponseHeadersRead);
}
but when sending PUT request I get:
Cannot close stream until all bytes are written.
Full exception info:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred while sending the request.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":"
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The request was aborted: The request was canceled.","ExceptionType":"System.Net.WebException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)\r\n
at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)\r\n
at System.Net.ConnectStream.Dispose(Boolean disposing)\r\n
at System.IO.Stream.Close()\r\n
at System.Net.Http.HttpClientHandler.<>c__DisplayClass109_0.<GetRequestStreamCallback>b__0(Task task)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Cannot close stream until all bytes are written.","ExceptionType":"System.IO.IOException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)"}}}
Inner exception :
IOException Message: "Cannot close stream until all bytes are
written." StackTrace: at
System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean
aborting)
Update:
Provided above code is fully working, the problem was how I attempted to use it. In my main API I had next webapi action:
[HttpPut]
public Task<HttpResponseMessage> Create(string id, Foo model)
{
return ForwardRequestToSomeApi();
}
The problem here is I introduced the model in parameters, thanks to model binding request's content were being read and parsed into model, so when I forward request to another API I send request without content. The fix is to remove all parameters:
[HttpPut]
public Task<HttpResponseMessage> Create()
{
return ForwardRequestToSomeApi();
}
Maybe I'm not understanding what a VirtualFileResult is, but I'm not sure why it's throwing a FileNotFoundException when the file exists. Here's the code:
if (System.IO.File.Exists(fileName))
{
FileInfo info = new FileInfo(fileName);
return File(fileName, FileUtility.GetContentType(fileName), info.Name);
}
(Edit: FileUtility.GetContentType (correctly) returns the Mime type of the file, which in my case is "application/pdf".)
Here's the exception I get: (I removed the file path)
System.IO.FileNotFoundException: Could not find file: [file path removed]
File name: '[file path removed]'
at Microsoft.AspNet.Mvc.VirtualFileResult.<WriteFileAsync>d__11.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.GetResult()
at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeResultAsync>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 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeResultFilterAsync>d__55.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAllResultFiltersAsync>d__54.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.GetResult()
at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeResourceFilterAsync>d__49.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAsync>d__44.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.GetResult()
at Microsoft.AspNet.Mvc.Infrastructure.MvcRouteHandler.<RouteAsync>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 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Routing.Template.TemplateRoute.<RouteAsync>d__27.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.GetResult()
at Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__9.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.GetResult()
at Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>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 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.IISPlatformHandler.IISPlatformHandlerMiddleware.<Invoke>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 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Diagnostics.StatusCodePagesMiddleware.<Invoke>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 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNet.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
It's seemingly bugging out even though an explicit check was done for whether the file exists or not. I can also manually confirm the file exists.
Maybe I'm not understanding what a VirtualFileResult is (File method returns this). On the documentation here it doesn't really describe what it is.
I'm using ASP.NET 5 RC1.
The method you're looking for is PhysicalFile():
return PhysicalFile(fileName, FileUtility.GetContentType(fileName), info.Name);
Beware, don't use a caller-supplied path with this.
The VirtualFileResult class needs the virtual path to the file in its constructor.
This means you need to provide the path relative to the wwwroot folder because it use HostingEnvironment's WebRootFileProvider.
private IFileProvider GetFileProvider(IServiceProvider requestServices)
{
if (FileProvider != null)
{
return FileProvider;
}
var hostingEnvironment = requestServices.GetService<IHostingEnvironment>();
FileProvider = hostingEnvironment.WebRootFileProvider;
return FileProvider;
}
}
Check the code on github
No luck with File("index.html") or File("~/index.html"), Virtualfileresult throws NotFound.
My solution was to use Microsoft.AspNetCore.Mvc.ControllerBase
method File(Stream fileStream...) :
public virtual FileStreamResult File(Stream fileStream,
string contentType, string fileDownloadName);
Index controller sample:
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
public class IndexController : Controller
{
ILoggerFactory Logger;
public IndexController(ILoggerFactory loggerFactory)
{
Logger = loggerFactory;
}
static string sep = Path.DirectorySeparatorChar.ToString();
[HttpGet("/index")]
[HttpGet("/")]
public IActionResult Index()
{
var log = Logger.CreateLogger("trace");
var path = $"{Startup.RootPath}{sep}index.html";
log.LogWarning(path);
Stream fileStream = new System.IO.FileStream(path, FileMode.Open);
return File(fileStream, "text/html");
}
}
// AspnetCore version 1.1.1 :
// <TargetFramework>netcoreapp1.1</TargetFramework>
// <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
Your VirtualFileResult must be a relative path from the application's wwwroot.
return File("~/foo.js","text/javascript")
is going to point to wwwroot/foo.js