Linq List to Byte Array - linq

I search in google, stackoverflow but did not get easy answer. Is there any way to convert a linq list to byte array?
public FileResult GetCustomerListCSV()
{
List<Customer> CustomerList = new List<Customer>();
CustomerList = dbContext.Customer.ToList(); // Need to convert this into byte array
return File(CustomerList, "text/csv", "CustomerList.csv");
}
Please help.

You have to create a CSV string first, then convert it to bytes:
var lines = CustomerList.Select(c => $"{c.Id}, {c.Name}");
var csv = string.Join(Environment.NewLine, lines);
var bytes = Encoding.UTF8.GetBytes(csv);
return File(bytes, "text/csv", "CustomerList.csv");
Alternatively, using CsvHelper library:
using var ms = new MemoryStream();
using var writer = new StreamWriter(ms);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(CustomerList);
csv.Flush();
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "text/csv", "CustomerList.csv");

Related

How to Insert data in Elastic Search

In my dotnet core project i need to insert data in elastic search. I am using bellow code for insert.
List<Patient> employeeData = null;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:5001/api/Employee/GetAll");
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var data= reader.ReadToEnd();
reader.Close();
dataStream.Close();
employeeData = JsonConvert.DeserializeObject<List<Employee>>(data);
}
var lst = employeeData;
int count = 0;
foreach (var obj in lst)
{
count ++;
this.client.Index(obj, i => i
.Index("employee")
.Type("myEmployee")
.Id(count)
// .Refresh()
);
}
After Execute the above code i am using bellow url for check the inserted data
localhost:9200/emp
I am getting following output.
{"emp":{"aliases":{},"mappings":{"myEmpl":{"properties":{"firstName":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"gEmailId":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"gMobile":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},"wmployeeID":{"type":"long"},"registrationNo":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}}}},"settings":{"index":{"creation_date":"1547020635852","number_of_shards":"5","number_of_replicas":"1","uuid":"6kle4jzMQDSICnPsmATbDw","version":{"created":"6050499"},"provided_name":"emp"}}}}
I am not able to see any of my data. What is the problem in this.
localhost:9200/emp returns the settings and mappings for index 'emp'. For the content, try localhost:9200/emp/_search.

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}

convert system.data.linq.binary to byte[]

I am storing bytes in a database table. When I retrieve it with Linq 2 sql I get the return type in system.data.linq.Binary.
I am not able to convert the system.data.linq.binary to byte array(byte[]).
How do I convert it?
///my datacontext
var db = new db();
//key is an value from user
var img = from i in db.images
where i.id == key
select i.data;
the i.data is in linq.binary I want it to be in byte[].
I tried with (byte[])img but it did not work.
Have you tried calling ToArray() on i.data?
var img = from i in db.images
where i.id == key
select i.data.ToArray();
System.Data.Linq.Binary has a ToArray method just for that purpose.
Probably its too late by now but may help others :)
//testTable PK:ID, binaryData :binary(32)
public void insertDummyData()
{
DBML.testTable v = new DBML.testTable ();
v.ID = 1;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
v.binaryData = new System.Data.Linq.Binary(encoding.GetBytes("11111111000000001111111100000000"));
db.testTable.InsertOnSubmit(v);
db.SubmitChanges();
}
Or else, Click on the Binary field from .dbml file, open properties and then change the field type from Binary to byte[] as found here
(byte[])linqBinaryField.ToArray()
You can try MemoryStream. I wrote a function in my project to convert an image to byte array like the following:
public static byte[] Image2ByteArr(string filename)
{
Bitmap bm = new Bitmap(getPath(filename));
MemoryStream ms = new MemoryStream();
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
Hope that helpful for you!

Export C# List to Csv file

I was trying to export my C# list to Csv file. All is set well. But the thing is field seperator is not working properly. its showing like, my string with " at the end (eg: 0000324df"). Here is my Controller code.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(String.Format("{0:d}", order.ItemNumber));
writer.Write("\"");
writer.Write(",");
writer.Write("\"");
writer.Write(order.Count);
writer.Write("\"");
writer.Write(",");
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");
I need to know how i can seperate the field values appropriately. Anyone can help me for this.
writer.Write("\"");
This line of code will be outputting a " every time. Why have it at all?
Also, I wouldn't have a comma before the WriteLine, since there is no need to delimit the end of the file.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(order.ItemNumber);
writer.Write(",");
writer.Write(order.Count);
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");

How to store a SyndicationFeed into an XDocument?

I'm programming a RSS Reader in Windows 8 (in C#) and I'm trying to pass a SyndicationFeed object into a XDocument. Does anyone know how to do this?
So far I have this.
SyndicationItem currentFeed = new SyndicationItem();
/* ... */
currentFeed = client.RetrieveFeedAsync(uri);
You've to parse its members as xml elements
var client = new SyndicationClient;
Stream st = await client.RetrieveFeedAsync(“http://example.com/feed.rss”);
using (StreamReader sr = new StreamReader(st)) {
string rss = sr.ReadToEnd();
}

Resources