วันจันทร์ที่ 27 กุมภาพันธ์ พ.ศ. 2560

Async-Await CSVHelper - CSVWriter

I want to write and send the CSV file over network stream (response to GET service). I familiar with CSVHelper, which provides function to read and write CSV file, I apply it to my project.

Unfortunately, the service throw me the some exceptions. I googled it and found this issue in JonhClose GitHub, John is the creator! He did not put this feature to avoid blocking task.

I try to apply CSVHelperAsync to my project. But it does not work for me.

Then,, why I write this blog??? I want to tel you that the best way to do is to generate the CSV yourself and attach it to the response Message.

[HttpGet]
[Route("DownloadCSV")]
public HttpResponseMessage GetCSVContentInfoByProduct(int productId)
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    MemoryStream stream = _business.GetCSV();
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    { FileName = "myCsv.csv" };
    return response;
}

public MemoryStream GetCSV()
{
    MemoryStream stream = new MemoryStream();
    string csv = <<your_csv_string>>;
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(csv);
    writer.Flush();
    stream.Position = 0;
    return stream;

}

Have fun :D

Cannot use string as an type-specific constraints

I am a starter in Web API. I try to implement GET service and use string as a constraint. VS throw me the error that.

------------------------------

Server Error in '/' Application.

The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'string'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'string'.