How to store a SyndicationFeed into an XDocument? - windows

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();
}

Related

Correct way to passed the stream image to tensorflow-lite model using Xamarin

im currently developing Image Classification using xamarin form, the model works well and the prediction result is good, but my problem is, it is only works in PickPhotoAsync passing to MediaFile then the MediaFile > get stream > get the byte > feed to model. i just used this for testing only
What i really need to do is to get the image from SignaturePad > get stream > get the Byte > feed to model
i got wrong prediction when i change it to signaturePad. i hope someone will help me, thank you in advance
here's my code.
protected async void PickPhotoAsync(object sender, EventArgs e)
{
var file = await CrossMedia.Current.PickPhotoAsync();
HandlePhoto(file);
}
private void HandlePhoto(MediaFile file)
{
var stream = file.GetStreamWithImageRotatedForExternalStorage();
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
var bytes = memoryStream.ToArray();
var len = stream.Length;
var pos = stream.Position;
var read = stream.CanRead;
var lens = bytes.Length;
List<ImageClassificationModel> classifyImage = DependencyService.Get<IClassify>().Classify(bytes);
var sortedList = classifyImage.OrderByDescending(x => x.Probability);
var top = sortedList.First();//Highest Prediction Result
var max = sortedList.Max(x => x.Probability);
}
Here is my code when i change it to SignaturePad (Source of image) which i got bad result
private async void SaveImagePad(object sender, EventArgs e)
{
Stream image = await PadView.GetImageStreamAsync(SignatureImageFormat.Png);
//get the stream from SignaturePad
if (image == null)
return;
BinaryReader br = new BinaryReader(image);
Byte[] All = br.ReadBytes((int)image.Length);
byte[] acImage = (byte[])All;
//Convert To Byte before passing to classifier
List<ImageClassificationModel> classifyImage = DependencyService.Get<IClassify>().Classify(acImage);
//File.Delete(path);
var sortedList = classifyImage.OrderByDescending(x => x.Probability);
var top = sortedList.First();
var max = sortedList.Max(x => x.Probability); // i got bad and random result
}

Linq List to Byte Array

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");

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!

Converting XDocument containing XDocumentType causes a NotSupportedException

I'm trying to create and export a XDocument on WP7.1.1 containing the following document type:
<!DOCTYPE xbel PUBLIC "+//IDN python.org//DTD XML Bookmark Exchange
Language 1.0//EN//XML"
"http://www.python.org/topics/xml/dtds/xbel-1.0.dtd">
Unfortunately I was greeted with NotSupportedExceptions in all my attempts so far and I don't know how to go from here. Here is a little excerpt of things I tried:
/* create document */
var document = new XDocument();
var doctype = new XDocumentType("xbel", null, null, null);
document.AddFirst(doctype); // << everything working without this line
/* document header */
var version = new XAttribute("version", "1.0");
var root = new XElement("xbel", version);
document.Add(root);
/* convert to string1 */
var text1 = document.ToString(); // << NotSupportedException was unhandled
/* convert to string2 */
var stringBuilder = new StringBuilder();
var stringWriter = new StringWriter(stringBuilder);
document.Save(stringWriter); // << NotSupportedException was unhandled
var text2 = stringBuilder.ToString();
This problem might be related to this and this question.
Here is a hacky solution for my specific problem:
/* format */
var stringBuilder = new StringBuilder();
var stringWriter = new StringWriter(stringBuilder);
document.Save(stringWriter);
var text = stringBuilder.ToString();
/* document type */
const string subset = "<!DOCTYPE xbel PUBLIC \"+//IDN python.org//DTD XML Bookmark Exchange Language 1.0" +
"//EN//XML\" \"http://www.python.org/topics/xml/dtds/xbel-1.0.dtd\">";
return text.Replace("?>", "?>" + Environment.NewLine + subset);
It's always sad when the shortcomings and bugs of a framework force you to write strange code like this, but it's even worse when those encounters are as frequent as they are with Windows Phone.

Resources