I am doing a project in C# using Winforms, and I want to create a Podcast RSS reader. So I have a XmlSerializer that saves a podcast entity to a podcastlist and I should then get a podcast.xml file in my project files that it then reads ( I guess). I got it to do exactly that, but with adding Categories. But when I want to read a URL that contains a RSS-file, it wont Save(Serialize) it using the XmlReader. Ive been staring at this for most of the day and I cant just figure out whats going wrong.
Here is my serializer and saved list of Podcasts.
protected string fileOfPodcasts = #"Podcasts.xml";
public List<Podcast> listOfPodcasts = new List<Podcast>();
public void SavePodcastList(List<Podcast> podcastList)
{
XmlSerializer xmlSerializer = new XmlSerializer(podcastList.GetType());
using (FileStream outFile = new FileStream(fileOfPodcasts, FileMode.Create,
FileAccess.Write))
{
xmlSerializer.Serialize(outFile, podcastList);
}
}
public List<Podcast> ReturnPodcasts()
{
List<Podcast> listOfPodcastsToBeReturned;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Podcast>));
using (FileStream inFile = new FileStream(fileOfPodcasts, FileMode.Open,
FileAccess.Read))
{
listOfPodcastsToBeReturned = (List<Podcast>)xmlSerializer.Deserialize(inFile);
}
return listOfPodcastsToBeReturned;
}
public void CreatePodcastObject ( string url, string interval, string category) // 3 parametrar
{
Podcast newPodcast = null;
{
newPodcast = new Podcast(url, interval, category);
}
podcastRepository.Create(newPodcast);
}
public void Create(Podcast entity)
{
podcastList.Add(entity);
SaveChanges();
}
Related
The problem is with built ASP.NET MVC solution uploaded on IIS in local network.
When I'm trying to upload file from other device than host, the target page is not loading.
When I'm trying to upload file from host is loading page without data from files.
All works fine when i'm running it in Visual Studio on my pc. The problem was made when i tried to run built solution o Windows Server.
What should I do? It is problem with IIS settings or with wrong code?
private void ReadFileFromStream(DateChoice datechoice, DateTime dateStartobj, DateTime dateEndobj, string FirstParameter_name, string SecondParameter_name, string ThirdParameter_name, string FourthParameter_name, string FivethParameter_name)
{
using (MemoryStream memoryStream = new MemoryStream())
{
datechoice.File.InputStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var streamReader = new StreamReader(memoryStream))
{
var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ";",
HasHeaderRecord = false
};
ReadCSV(dateStartobj, dateEndobj, streamReader, csvConfig, FirstParameter_name, SecondParameter_name, ThirdParameter_name, FourthParameter_name, FivethParameter_name);
}
}
}
private void ReadCSV(DateTime dateStartobj, DateTime dateEndobj, StreamReader streamReader, CsvConfiguration csvConfig, string FirstParameter_name, string SecondParameter_name, string ThirdParameter_name, string FourthParameter_name, string FivethParameter_name)
{
using (var csvReader = new CsvReader(streamReader, csvConfig))
{
var records = csvReader.GetRecords<Read>().ToList();
List<DataPoint> Parametry_A, Parametry_B, Parametry_C, Parametry_D, Parametry_E;
NewListDeclarate(out Parametry_A, out Parametry_B, out Parametry_C, out Parametry_D, out Parametry_E);
foreach (var record in records)
{
if (DateVerification(record))
{
DateTime label_date;
DataPoint dataPointA, dataPointB, dataPointC, dataPointD, dataPointE;
NewPointsGenerate(record, out label_date, out dataPointA, out dataPointB, out dataPointC, out dataPointD, out dataPointE, FirstParameter_name, SecondParameter_name, ThirdParameter_name, FourthParameter_name, FivethParameter_name);
if (UserDateCheck(dateStartobj, dateEndobj, label_date))
{
AddPointsToList(Parametry_A, Parametry_B, Parametry_C, Parametry_D, Parametry_E, dataPointA, dataPointB, dataPointC, dataPointD, dataPointE);
}
}
}
ReturnListsToViewBag(Parametry_A, Parametry_B, Parametry_C, Parametry_D, Parametry_E);
}
}
I'am trying to not create a file, and pass xml document straight to a SkiaSharp method Load. I mean, is there the way to imitate a path? So here is the code:
public IActionResult svgToPng(string itemId, string mode = "
{
var svgSrc = new XmlDocument();
svgSrc.LoadXml(/*Some xml code*/);
string svgSaveAs = "save file path";
var quality = 100;
var svg = new SkiaSharp.Extended.Svg.SKSvg();
var pict = svg.Load(svgSrc); // HERE, it needs to be a path, not XmlDocument, but i want to pass straight
var dimen = new SkiaSharp.SKSizeI
(
(int) Math.Ceiling(pict.CullRect.Width),
(int) Math.Ceiling(pict.CullRect.Height)
);
var matrix = SKMatrix.MakeScale(1, 1);
var img = SKImage.FromPicture(pict, dimen, matrix);
// Convert to PNG
var skdata = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality);
using(var stream = System.IO.File.OpenWrite(svgSaveAs))
{
skdata.SaveTo(stream);
}
ViewData["Content"] = "PNG file was created out of SVG.";
return View();
}
The Load method seems to be this:
public SKPicture Load(
using (var stream = File.OpenRead(filename))
{
return Load(stream);
}
}
look at the code of that library :
https://github.com/mono/SkiaSharp.Extended/blob/master/SkiaSharp.Extended.Svg/source/SkiaSharp.Extended.Svg.Shared/SKSvg.cs
Look at the Load method, it has multiple implementations :
public SKPicture Load(string filename)
{
using (var stream = File.OpenRead(filename))
{
return Load(stream);
}
}
public SKPicture Load(Stream stream)
{
using (var reader = XmlReader.Create(stream, xmlReaderSettings, CreateSvgXmlContext()))
{
return Load(reader);
}
}
public SKPicture Load(XmlReader reader)
{
return Load(XDocument.Load(reader));
}
You will need to pick one of them and use it. Now, nothing stops you from getting the code and adding one extra Load for an XML string for example, but since this is a library you do not control, I'd stick to what you are given.
You could use the XmlReader version, that's probably the closest one to what you want.
I'm using winforms and c# to save data in xml file. I successfully insert my data into the xml file and display it in my winform but the problem is when i close and open again the form to save again another data the system display this message:
"The process can't access to the file "xmlfile path" because it's
being in use by another process"
I´m using the code below:
class information.cs:
private string id_x;
private string id_y;
private string fname_x;
private string fname_y;
public string ID_X
{
get { return id_x; }
set { id_x = value; }
}
public string ID_Y
{
get { return id_y; }
set { id_y = value; }
}
public string Fname_X
{
get { return fname_x; }
set { fname_x = value; }
}
public string Fname_Y
{
get { return fname_y; }
set { fname_y = value; }
}
Class saveXML.cs:
public static void SaveData(object obj, string filename)
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer,obj);
writer.Close();
}
in the load form:
if (File.Exists("Patient_Data.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read);
Information info = (Information)xs.Deserialize(read);
int x1 = Int32.Parse(info.ID_X);
int y1 = Int32.Parse(info.ID_Y);
int x2 = Int32.Parse(info.Fname_X);
int y2 = Int32.Parse(info.Fname_Y);
this.tlp_id.Location = new Point(x1, y1);
this.tlp_fname.Location = new Point(x2, y2);
Your are not closing the FileStream after you have read all information from it.
FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read);
Information info = (Information)xs.Deserialize(read);
read.Close();
A better way to ensure that also in case of an exception the FileStream is closed, is to use a using-statement.
using(FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read)) {
Information info = (Information)xs.Deserialize(read);
}
I created a homescreen widget, that gets a table of strings from a website. Instead of getting data from web on every update, I want to save the table to the phone and than read from the file on update. I'm using Mono for Android (C#).
Here is a method for saving data to the file system using XML Serialization
public static bool SaveData<T>(Context context, string fileName, T data)
{
try
{
using (Stream stream = context.OpenFileOutput(fileName, FileCreationMode.Private))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stream, data);
}
return true;
}
catch (Exception)
{
return false;
}
}
And here is a method for loading serialized data from the file system
public static T LoadData<T>(Context context, string fileName)
{
Java.IO.File file = context.GetFileStreamPath(fileName);
if (file.Exists())
{
using (Stream openStream = context.OpenFileInput(fileName))
{
using (StreamReader reader = new StreamReader(openStream))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
var loadedObject = serializer.Deserialize(reader);
return (T)loadedObject;
}
catch (Exception ex)
{
// TODO Handle error
return default(T);
}
}
}
}
else
{
throw new Java.IO.FileNotFoundException("Could not find file " + fileName);
}
}
Using these methods you can easily save and load any serializable object such as a string[] you retrieved from the website.
string[] data = { "one", "two", "three" };
JavaIO.SaveData(this, "SavedData.txt", data);
string[] loadedData = JavaIO.LoadData<string[]>(this, "SavedData.txt");
If it's just a simple list, then you can use System.IO.File to load/save text - and you can use something like JSON.Net to convert your list to/from text.
If your data is more incremental, then you can use SQLite instead - try the the SQLite-net ORM wrapper on GitHub
I'm developing a web app with mongodb as my back-end. I'd like to have users upload pictures to their profiles like a linked-in profile pic. I'm using an aspx page with MVC2 and I read that GridFs library is used to store large file types as binaries. I've looked everywhere for clues as how this is done, but mongodb doesn't have any documentation for C# api or GridFs C#. I'm baffled and confused, could really use another set of brains.
Anyone one know how to actually implement a file upload controller that stores an image uploaded by a user into a mongodb collection? Thanks a million!
I've tried variations of this to no avail.
Database db = mongo.getDB("Blog");
GridFile file = new GridFile(db);
file.Create("image.jpg");
var images = db.GetCollection("images");
images.Insert(file.ToDocument());
Following example show how to save file and read back from gridfs(using official mongodb driver):
var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("tesdb");
var fileName = "D:\\Untitled.png";
var newFileName = "D:\\new_Untitled.png";
using (var fs = new FileStream(fileName, FileMode.Open))
{
var gridFsInfo = database.GridFS.Upload(fs, fileName);
var fileId = gridFsInfo.Id;
ObjectId oid= new ObjectId(fileId);
var file = database.GridFS.FindOne(Query.EQ("_id", oid));
using (var stream = file.OpenRead())
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
using(var newFs = new FileStream(newFileName, FileMode.Create))
{
newFs.Write(bytes, 0, bytes.Length);
}
}
}
Results:
File:
Chunks collection:
Hope this help.
The answers above are soon to be outdated now that the 2.1 RC-0 driver has been released.
The way to work with files in v2.1 MongoDB with GridFS can now be done this way:
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System.IO;
using System.Threading.Tasks;
namespace MongoGridFSTest
{
class Program
{
static void Main(string[] args)
{
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("TestDB");
var fs = new GridFSBucket(database);
var id = UploadFile(fs);
DownloadFile(fs, id);
}
private static ObjectId UploadFile(GridFSBucket fs)
{
using (var s = File.OpenRead(#"c:\temp\test.txt"))
{
var t = Task.Run<ObjectId>(() => { return
fs.UploadFromStreamAsync("test.txt", s);
});
return t.Result;
}
}
private static void DownloadFile(GridFSBucket fs, ObjectId id)
{
//This works
var t = fs.DownloadAsBytesByNameAsync("test.txt");
Task.WaitAll(t);
var bytes = t.Result;
//This blows chunks (I think it's a driver bug, I'm using 2.1 RC-0)
var x = fs.DownloadAsBytesAsync(id);
Task.WaitAll(x);
}
}
}
This is taken from a diff on the C# driver tests here
This example will allow you to tie a document to an object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MongoServer ms = MongoServer.Create();
string _dbName = "docs";
MongoDatabase md = ms.GetDatabase(_dbName);
if (!md.CollectionExists(_dbName))
{
md.CreateCollection(_dbName);
}
MongoCollection<Doc> _documents = md.GetCollection<Doc>(_dbName);
_documents.RemoveAll();
//add file to GridFS
MongoGridFS gfs = new MongoGridFS(md);
MongoGridFSFileInfo gfsi = gfs.Upload(#"c:\mongodb.rtf");
_documents.Insert(new Doc()
{
DocId = gfsi.Id.AsObjectId,
DocName = #"c:\foo.rtf"
}
);
foreach (Doc item in _documents.FindAll())
{
ObjectId _documentid = new ObjectId(item.DocId.ToString());
MongoGridFSFileInfo _fileInfo = md.GridFS.FindOne(Query.EQ("_id", _documentid));
gfs.Download(item.DocName, _fileInfo);
Console.WriteLine("Downloaded {0}", item.DocName);
Console.WriteLine("DocName {0} dowloaded", item.DocName);
}
Console.ReadKey();
}
}
class Doc
{
public ObjectId Id { get; set; }
public string DocName { get; set; }
public ObjectId DocId { get; set; }
}