i am using MimeKit 3.2.0 and Google.Apis.Gmail.v1 1.57.0.2622.
i keep getting error `System.FormatException: Failed to parse message headers.`
Here's the code below, what is the problem here? i've searched everywhere and couldn't find a solution
The service here is a GmailService object, totally functional
var requestMessage = _service.Users.Messages.Get("me", message.Id);
requestMessage.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
await using var rawStream = await requestMessage.ExecuteAsStreamAsync();
var mimeMsg = MimeMessage.Load(rawStream);
i also tried to inject the stream into a Filtered stream object , but that didn't help
it looks like this
using (var filtered = new FilteredStream(rawStream))
{
filtered.Add(DecoderFilter.Create(ContentEncoding.Base64));
var mimeMsg = await MimeMessage.LoadAsync(filtered);
}
Related
I am developing (so new at it) an application with Windows Forms C# in Visual Studio and I need to get a specific commit from a GitLab project.
I have seen many examples about for GitHub. I have tried this way (do not know if is the correct one):
Download repository at a particular commit using the 7-digit SHA1:
var Token = "xxxx";
var url = "http://{my_domain}/{user}/{project_name}/repository/archive/{shor_id}.zip";
var path = #"C:\GitLab\My_Projects";
try
{
using (var client = new System.Net.Http.HttpClient())
{
var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", Token);
credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
var contents = client.GetByteArrayAsync(url).Result;
System.IO.File.WriteAllBytes(path, contents);
}
}
catch (System.UnauthorizedAccessException)
{
backgroundWorker1.CancelAsync();
Console.WriteLine("Problem downloading");
}
But I get this error:
'System.UnauthorizedAccessException' in mscorlib.dll. Access denied to 'C:\GitLab\My_Projects'.
As I said before, I am new at it and probably may have said something stupid, sorry in advance.
If someone knows about the subject, I would love to explain or help me with this concept.
Finally, I achived the solution. I took another direction using GitLab API.
If someone would like to look at the result I arrived, here you have the code:
var url_sha = $"http://{my_gitlab_domain}/api/v4/projects/{id_project}/repository/archive.zip?
private_token={my_token}&sha={short_id_commit}";
var client = new HttpClient();
var response = await client.GetAsync(url_sha);
var local_path = #"C:\GitLab\My_Projects";
using (var stream = await response.Content.ReadAsStreamAsync())
{
var fileInfo = new FileInfo(local_path + ".zip");
using (var fileStream = fileInfo.OpenWrite())
{
await stream.CopyToAsync(fileStream);
}
}
I have a .NET Core 3 MVC app that needs to read a file from one location over HTTP and then re-deliver it back out to the response. Some of these files will be ~200MB in size.
What I have works, but it reads the whole file into memory before sending the File result out to the client. Is there a way to make it essentially a passthrough where the read stream flows into the response stream so that very little memory is required on the server?
This is what I have now but I do not think will perform well with large files:
if (requestedFile != null)
{
using (var client = new System.Net.Http.HttpClient())
{
using (var result = await client.GetAsync(requestedFile.DownloadUrl))
{
if (result.IsSuccessStatusCode)
{
var bytes = await result.Content.ReadAsByteArrayAsync();
return File(bytes, "application/zip", "largefile.zip");
}
}
}
}
I have also tried this which results in a runtime error of "Cannot access a closed Stream":
using (var client = new System.Net.Http.HttpClient())
{
using (var httpResponseMessage = await client.GetAsync(requestedFile.DownloadUrl))
{
return File(await httpResponseMessage.Content.ReadAsStreamAsync(), "application/zip", "largefile.zip");
}
}
Edit:
Solution after some trial and error was remocing all using statements and letting the FileStreamResult close the stream on its own. So I ended up with:
var client = new HttpClient();
var result = await client.GetAsync(requestedFile.DownloadUrl);
var stream = await result.Content.ReadAsStreamAsync();
return new FileStreamResult(stream, "application/zip")
{
FileDownloadName = "largefile.zip"
};
One of the overloads for File is a Stream. Just get that URL as a Stream or read the response body as a stream and immediately return that in the overload:
var client = new System.Net.Http.HttpClient();
var result = await client.GetAsync(requestedFile.DownloadUrl);
var stream = await result.Content.ReadAsStreamAsync();
return File(stream,"application/pdf", "Invoice.pdf");
Note: this will fail if you wrap the Stream in a using block as the FileResult already closes the Stream.
For Export Excel
var client = new System.Net.Http.HttpClient();
var comp = client.GetAsync($"RewardEmployee/ExportExcelCalculate?rewardConfigId={id}").Result;
`var stream = await result.Content.ReadAsStreamAsync();
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ExportExcelCalculateRewardEmployee.xlsx");
I've been trying to get a grasp on C#/.NET and UWP applications. At the moment I'm trying to follow this guide to complete CRUD operations against my database. So far so good, but when I come to the part where I want to create I run into som troubles. The code below is where I create a new object and try to post it to the database. Piece in this context is a book.
var newPiece = new Piece
{
PieceTitle = Title.Text,
PieceAuthor = Author.Text,
PieceIsbn = Isbn.Text,
PieceDescription = Description.Text
};
using (var client = new HttpClient())
{
var content = JsonConvert.SerializeObject(newPiece);
Task task = Task.Run(async () =>
{
var data = new HttpFormUrlEncodedContent(
new Dictionary<string, string>
{
["value"] = content
});
await client.PostAsync(App.BaseUri, data);
});
task.Wait();
}
The problem here is that because I am using both HttpClient() and HttpFormUrlEncodedContent() VS is telling me that HttpClient() is "an ambiguous reference" and that I need to specify if it belongs to System.Net.Http; or Windows.Web.Http;. If I choose System.Net.Http then it tells me that Argument 1 in PostAsync() "cannot be converted from 'System.Uri' to 'string'", and that Argument 2 "cannot convert from 'Windows.Web.Http.HttpFormUrlEncodedContent' to 'System.Net.Http.HttpContent'"
If I try letting HttpClient() use Windows.Web.Http; then it doesn't give me any errors while compiling, but after the object has been created and posted it displays as null in my tables.
System.Net.Http name space has FormUrlEncodedContent. You can use that.
var newPiece = new Piece
{
PieceTitle = Title.Text,
PieceAuthor = Author.Text,
PieceIsbn = Isbn.Text,
PieceDescription = Description.Text
};
using (var client = new System.Net.Http.HttpClient()) {
var json = JsonConvert.SerializeObject(newPiece);
var content = new System.Net.Http.FormUrlEncodedContent(
new Dictionary<string, string> {
["value"] = json
});
await client.PostAsync(App.BaseUri, content);
}
Should also try to avoid mixing async and blocking calls like .Wait() or .Result as they can lead to deadlocks.
It was also indicated that the data when received is null. This could be an indication that the format being used does not match the expected format.
Try using a different format. For example the following sends JSON content.
using (var client = new System.Net.Http.HttpClient()) {
var json = JsonConvert.SerializeObject(newPiece);
var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
await client.PostAsync(App.BaseUri, content);
}
I am working on a Windows to UWP app. A web service exists that when called (GET), returns a file. When the web service is triggered using a browser, it successfully downloads a file on the browser.
On the UWP app, I am using Windows.Web.Http to call the web service. I need to save get the file sent by the web service and save it on the device.
I currently have the following code. Not sure how to get the result from the web service and save to the file.
public async Task DownloadFile(string WebServiceURL, string PathToSave)
{
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
{
//not sure if this is correct and if it is, how to save this to a file
}
}
Using System.Web.Http, I am able to easily do this using the following:
Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();
However, using Windows.Web.Http, I am not sure how I can do this. Please help!
this what you looking for?
like this?
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
//not sure if this is correct and if it is, how to save this to a file
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await result.Content.WriteToStreamAsync(filestream);
await filestream.FlushAsync();
}
I am trying to call method created correctly using WCF, I start debugging the project for WCF and the result as the following:
on my xamarin.forms code i used HttpClient Library as the following:
private async Task DownloadInfo()
{
var Uri = "http://localhost:10300/RestServiceImpl.svc/json";
var httpClient = new HttpClient();
var json= await httpClient.GetStringAsync(Uri);
}
when I am trying to get json result from Xamarin.Forms I get the following:
what I should do?
It seems like you are inspecting the task there, this doesnt give that much information. You can try this little more structured approach.
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:10300");
var request = "/RestServiceImpl.svc/json";
var result = await httpClient.GetAsync(request);
if (!result.IsSuccessStatusCode)
throw new HttpRequestException($"{result.StatusCode} \n {result.Content.ReadAsStringAsync().Result} \n\n {httpClient.BaseAddress}{request}");
var json = await result.Content.ReadAsStringAsync();
Debug.WriteLine(json);
}