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!
Related
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");
hi guys this is my first time using Sqlite, i managed to retrieve the text and display it, however the image shows a red question mark even tho i followed this : unity sqlite tutorial
here is my code :
private void readQuestionsFromDB(){
string conn = "URI=file:" + Application.dataPath + "/quizdb.s3db"; //Path to database.
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT id, statement, answer, image " + "FROM questions";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string statement = reader.GetString(1);
answerint = reader.GetInt32(2);
byte[] img = (byte[])reader["image"];
Question q = new Question(statement, answer, img);
questions.Add(q);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
Then i try to display the image from the start method :
readQuestionsFromDB();
statement.text = questions[0].statement;
Texture2D tex = new Texture2D(800,400); //image is 800/400
tex.LoadImage(questions[0].image);
image.GetComponent<Image>().sprite = Sprite.Create(tex, new Rect(0,0,tex.width,tex.height),new Vector2(0.5f, 0.5f));
Here is the outcome :
image
Thank you in advance for your help!
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;
}
}
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();
}
Hello the app that I'm building works with alot of images that are stored on the server and need to display them on a listview. I would like to be able to store them on a file.
so far here is the code I have
var imageUrl = new Java.Net.URL(obj.imageUrl);
var bitmap = Android.Graphics.BitmapFactory.DecodeStream(imageUrl.OpenStream());
var image = new Android.Graphics.Drawables.BitmapDrawable(bitmap);
but I don't know how to save the image or where to save it.
any help?
thanks
You're overthinking this. :-)
Once you have a Stream:
var imageUrl = new Java.Net.URL(obj.imageUrl);
System.IO.Stream stream = imageUrl.OpenStream();
you can just save it to disk:
using (var o = File.Open(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"file-name"))) {
byte[] buf = new byte[1024];
int r;
while ((r = stream.Read(buf, 0, buf.Length)) > 0)
o.Write (buf, 0, r);
}
Environment.GetFolderPath(Environment.SpecialFolder.Personal) returns $APPDIR/files, which is Context.FilesDir. You don't necessarily need to use this; Context.CacheDir may be more appropriate.