How to let user click to open the CSV file in browser C# BotFramework SDK3 - botframework

As the title, I want to let user click to open a file in browser which is created by Bot. I'm using webChat.
The code is what I have tried.
In botframework-emulator, if I click the link, the CSV file will open in the browser.
But in the webChat, it will request user to download, not open in the browser.
var aaa = await GetCSVAttachmentAsync(replymes.ServiceUrl, replymes.Conversation.Id);
foreach(var aa in aaa)
replymes.Attachments.Add(aa);
await context.PostAsync(replymes);
private async Task<IList<Attachment>> GetCSVAttachmentAsync(string serviceUrl, string conversationId)
{
string str = "this is a text CSV";
byte[] array = Encoding.GetEncoding("shift_jis").GetBytes(str);
using (var connector = new ConnectorClient(new Uri(serviceUrl)))
{
var attachments = new Attachments(connector);
var response = await attachments.Client.Conversations.UploadAttachmentAsync(
conversationId,
new AttachmentData
{
Name = "userinfo.csv",
OriginalBase64 = array,
Type = "text/csv"
});
message.Add(new Attachment
{
Name = "userinfo.html",
ContentType = "text/html",
ContentUrl = response.Id
});
return message;
}
}
To solve this problem, I also tried storageV2. But it seems the URI can't be accessed directly.

I still couldn't figure it out without creating a real file.
But instead of using storage V2, I can solve the problem. The thought is as below.
Let the bot create a file.
Upload it to Storage V2 using static website
Send the static website to user.

Related

How can i upload a media file to my google drive using google api?

Hey im trying to upload certain media files to my google drive using google api services can someone please tell me how can i do it, in my previous question i have given the code for getservice and clientservice you could refer to that thankyou
Uploading a file to Google drive is reasonably strait forward.
authorize the user.
create the file metadata
upload the file data itself
I have serval tutorials on this topic and a YouTube video This should get you started.
How to upload a file to Google Drive with C# .net
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Upload;
Console.WriteLine("Hello, World!");
// Installed file credentials from google developer console.
const string credentialsJson = #"C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json";
// used to store authorization credentials.
var userName = "user";
// scope of authorization needed from the user
var scopes = new[] { DriveService.Scope.Drive };
// file to upload
var filePath = #"C:\Development\FreeLance\GoogleSamples\Data\image.png";
var fileName = Path.GetFileName(filePath);
var folderToUploadTo = "1hwRZWAi-OznYGL51Yx9BJmDp5Ayips16";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(credentialsJson).Secrets,
scopes,
userName,
CancellationToken.None).Result;
// Create the Drive service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Daimto Drive upload Quickstart"
});
// Upload file photo.jpg on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string>() { folderToUploadTo }
};
var fsSource = File.OpenRead(filePath);
// Create a new file, with metadatafileName and stream.
var request = service.Files.Create(fileMetadata, fsSource, "image/jpeg");
request.Fields = "id";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
var fileId = request.ResponseBody?.Id;
Console.WriteLine($"fileId {fileId}");
Console.ReadLine();

Client-Side error when uploading image on server ASP.NET Core

I am struggling with uploading an image from thew client-side to a folder on the server-side in .Net Core.I used Postman to check if the method on the server-side is working and it does without any problem,but when I try to upload an image from the client-side,I get an error on the server-side of type NullReferenceException:Object reference not set to an instance of an object.This is the Post method on the server-side:
[HttpPost]
public async Task Post(IFormFile file)
{
if (string.IsNullOrWhiteSpace(_environment.WebRootPath))
{
_environment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
//var fileName = file.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
if (!Directory.Exists(uploads)) Directory.CreateDirectory(uploads);
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
Apparently the method is thrown where I check if the length of the file is bigger than 0.On the client-side I get error "500 internal server error" and I tried to check using the debugger where exactly the error is thrown but i can't find anything that could resemble an error of some sort.This is the API method for the client-side:
public async Task UploadPictureAsync(MediaFile image)
{
User user = new User();
string pictureUrl = "http://10.0.2.2:5000/api/UploadPicture";
HttpContent fileStreamContent = new StreamContent(image.GetStream());
// user.Picture=GetImageStreamAsBytes(image.GetStream());
fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {FileName=Guid.NewGuid() + ".Png",Name="image"};
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient(clientHandler))
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent);
var response = await client.PostAsync(pictureUrl, formData);
if(response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
}
}
The image is declared in the Model as byte array:
public byte[] Picture { get; set; }
Does someone understand why my POST method has this behavior since the server-side works perfectly but fails when I try to upload an image from the client-side?What I find weird though is that when i read the error and I look at the Content-Type it is "text/plain" instead of "form-data" and I have tried to set it at the MutipartFormDataContent like this:
formData.Headers.ContentType.MediaType = "multipart/form-data";
I also tried to set the MediaTypeHeaderValue on the client like this:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
I still get the wrong content type.
I have also tried a different approach with Stream instead of MediaFile but without any luck as it did not even hit the break point in debugger mode for the response.Any help would be appreciated! :)
I have managed to find the answer finalllyyyyy!!!The problem was on the client-side as I suspected and guess what,it was all about the correct name.It turns out that since on the server side I have IFormFile file I had to change the client side to take the parameter name "file" instead of image as well so that it could work.Thank you #Jason for the suggestions as I didn't understand the error from the first place and did some debugging on the server-side to help me figure it out.

Skype: Not able to send file attachment to user

I am not able to send file attachment from a bot to a user in Skype. I am using bot builder version 3.5.0.
Below is my code.
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
Activity reply = activity.CreateReply("blah");
reply.Attachments = new List();
Attachment attach = new Attachment();
attach.ContentType = "application/pdf";
// I can browse the below URL in browser and access the PDF
attach.ContentUrl = "https://test.azurewebsites.net/Image/Test.pdf";
attach.Name = "Test.pdf";
attach.Content = "Test";
attach.ThumbnailUrl = attach.ContentUrl;
reply.Attachments.Add(attach);
await connector.Conversations.ReplyToActivityAsync(reply);
Aside from the dire need to upgrade your version of botbuilder, there is also a sample for this. please refer to it for further guidance. It is located in the botbuilder-samples repo. in the sample they are constructing the attachments very similar to how you are:
private static Attachment GetInternetAttachment()
{
return new Attachment
{
Name = "BotFrameworkOverview.png",
ContentType = "image/png",
ContentUrl = "https://learn.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png"
};
}
So this is most likely caused by the very outdated version of botbuilder you are using

How do I send a base64 encoded PDF file?

I want my bot to send a PDF file to the user. I have the PDF as a base64 string and tried to send it through an attachment:
Attachment attachment1 = new Attachment();
attachment1.Name = "name.pdf";
attachment1.ContentType = "application/pdf";
attachment1.ContentUrl = "data:application/pdf;base64," + base64String;
var m = context.MakeMessage();
m.Attachments.Add(attachment1);
m.Text = "File";
await context.PostAsync(m);
Within the emulator, it just doesn't work but in the channels Telegram and Facebook (which I need), the bot just outputs an error...
Has someone already succeed in it?
Note: Using an HTTP address works fine, but I need to use the base64 string
As this method in botframework call sendDocument method of Telegram, and this method in its document property get http url or a file_id, so you can't pass base64String to this method as a valid document type.
You can follow the valid type of the document passing into the telegram in this link (also, see the following image).
The pdf file must be embedded resource. Hope it help.
if (this.channelid == "telegram")
{
var url = string.Format("https://api.telegram.org/bot{0}/sendDocument", Settings.tokentelegram);
Assembly _assembly;
Stream file;
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(this.chat_id, Encoding.UTF8), "chat_id");
_assembly = Assembly.GetExecutingAssembly();
file = _assembly.GetManifestResourceStream("Namespace.FolderResourses.name.pdf");
form.Add(new StreamContent(file), "document", "name.pdf");
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}

Read both key values and files from multipart from data post request in ASP.NET WebAPI

I have an endpoint that needs to accept a file upload and also some other information from the client request. With the following code I can upload the file successfully but can't seem to figure out how to read the other info.
I make a test request from Postman with the following form data:
image -- myimage.jpg -- of type File
email -- a#b.com -- of type Text
The backend code looks like this:
[HttpPost]
public async Task<HttpResponseMessage> SharePhoto()
{
try
{
var provider = new MultipartMemoryStreamProvider();
var data = await Request.Content.ReadAsMultipartAsync(provider);
// this is how I get the image which I am succesfully passing to EmailService
var item = (StreamContent)provider.Contents[0];
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
String emailAddress;
EmailService.SendSharedPhoto(emailAddress, stream);
return Request.CreateResponse();
}
}
catch
{
// do stuff
}
}
In this example I am able to access provider.Contents[1] but can't seem to be able to get the value from it into emailAddress. I'm thinking it may be possible to use the same trick as the await item.CopyToASync(stream) from the image upload, but I'm hoping I can get a simpler solution to that. Any ideas?
I just barely answered a very similar question to this yesterday. See my answer here complete with sample controller code.
The method I ended up using is:
If the form elements are strings (and it worked for me since the mobiel frontend took responsability for input data) you can do this:
var streamContent = (StreamContent)provider.Contents[1];
var memStream = new MemoryStream();
await streamContent.CopyToAsync(memStream);
var actualString = Encoding.UTF8.GetString(x.ToArray());
If however the field needs to represent a collection of items, like for example the email list: ["a#b.com", "x#c.com"], etc a JavaScriptSerializer can be user, like so:
var streamContent = (StreamContent)provider.Contents[1];
var emailAddresses = await str.ReadAsStringAsync();
var jsSerializer = new JavaScriptSerializer();
var deserializedData = jsSerializer.Deserialize<string[]>(emailAddresses);
Note that this is nowhere near safe, though it is few lines of code and happens to work.

Resources