An Error occured while parsing EntityName. Line 32, position 51 - c#

I've tried looking at several different methods revolving around using XDocument class to load my xml file. However, this error and other variations have been appearing. If I use the absolute path, it displays an error of it cannot find the file.
The issue is my xml file has a combination of both English and Japanese used in it. The link should allow for anyone to view the xml file.
Here is my code and xml file:
public partial class MainWindow : Window
{
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0";
public MainWindow()
{
InitializeComponent();
XMLViewer();
}
private void XMLViewer()
{
try
{
XDocument Doc = XDocument.Load(URLSource);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}

The URL you use don't contain a XML document but an HTML page :
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0
You need to change the value of dl to 1, so Dropbox will return your XML document:
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1

As #Florian said you should use second link, but maybe you have problem to read unicode xml, so its better using Request and ResponseStream:
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1";
private void XMLViewer()
{
try
{
var request = (HttpWebRequest)WebRequest.Create(URLSource);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream, true))
{
XDocument Doc = XDocument.Load(sr);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

Related

C# (xamarin project) not able to find path to the file

I have this problem when I'm trying to read JSON file (or any file): It's not able to find that file. I try everything, even the absolute path (error almost same - DirectoryNotFound)
This is structure of mine code:
And this is code:
private void LoadJson()
{
using (var r = new StreamReader("quizQuestions.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}
I I even try to use Directory.GetCurrentDirectory() but it's returning : / -> only this character. I don't know where is a mistake or if I forgot to set something. I try to find answers everywhere but I was not able to find anything with this.
Make sure the Build Action of the file is set as Content or as an Asset and give this a try.
private void LoadJson()
{
AssetManager assets = this.Assets;
using (var r = new StreamReader(assets.Open ("quizQuestions.json")))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}
You can configure the file as Embedded Resource and then access it like this:
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourceNames = assembly.GetManifestResourceNames();
var resourcePaths = resourceNames
.Where(x => x.EndsWith(resourceFileName, StringComparison.CurrentCultureIgnoreCase)).ToArray();
if (resourcePaths.Any() && resourcePaths.Count() == 1)
{
return assembly.GetManifestResourceStream(resourcePaths.Single());
}
return null; // or throw Exception
}
private void LoadJson()
{
Assembly assembly = GetAssemblyContainingTheJson();
using (var r = GetEmbeddedResourceStream(assembly, "quizQuestions.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}

How to pass xml file inside of code instead of a folder path?

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.

Elency Solutions CSV Library Error C#

I am using the elency solutions CSV library for C# to save and load some data from a file.
My code saves and loads correctly, but when I load and then try to save an error occurs, saying that another process is using the file.
The load method is this:
private void loadfile(string name)
{
int key = 696969;
CsvReader read = new CsvReader("data.csv");
try
{
do
{
read.ReadNextRecord();
} while (name != read.Fields[0]);
int decAgain = int.Parse(read.Fields[1], System.Globalization.NumberStyles.HexNumber); //convert to int
int dec = decAgain ^ key;
MessageBox.Show(dec.ToString());
}
catch (Exception)
{
MessageBox.Show("Not Found");
}
read = null;
}
As you can see, I am sort of disposing the "read" object.
Here is the save method:
private void savefile(string encrypted, string name)
{
CsvFile file = new CsvFile();
CsvRecord rec = new CsvRecord();
CsvWriter write = new CsvWriter();
rec.Fields.Add(name);
rec.Fields.Add(encrypted);
file.Records.Add(rec);
write.AppendCsv(file, "data.csv");
file = null;
rec = null;
write = null;
}
It always gets stuck on append csv.
I do understand the problem. The reader is not being closed successfully. How can I correctly close the file?
NB: I have tried read.Dispose() but it is not working.
Can you please help me out?
Regards
Use using to automatically dispose object. It may solve your issue.
private void savefile(string encrypted, string name)
{
using(CsvFile file = new CsvFile())
{
using(CsvRecord rec = new CsvRecord())
{
using(CsvWriter write = new CsvWriter())
{
rec.Fields.Add(name);
rec.Fields.Add(encrypted);
file.Records.Add(rec);
write.AppendCsv(file, "data.csv");
}
}
}
}

Load a xml file using XDocument.Load from FileSystemWatcher. Error "The process cannot access the file..etc"

Is there a way to fix the error "The process cannot access the file..etc". The flow is that the filesystemwatcher will watch for a xml file when I detects a xml file i need to read a specific node from the xml file.
How can I fix this? Any ideas or suggestions will be a big help. Thanks
Here is the filesystemwatcher code
private void fileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
try
{
string type = GetType(e.FullPath).ToUpper();
if (type == "CC")
{
if (Global.pc_flag)
{
ProcessPC(e.FullPath);
}
else if (Global.mw_flag)
{
ProcessMW(e.FullPath);
}
else
{
ProcessXML(e.FullPath);
}
}
else if (type == "GC")
{
ProcessMW(e.FullPath);
}
//Process(e.FullPath);
}
catch(Exception ex)
{
error++;
lblErrors.Text = error.ToString();
MessageBox.Show(ex.Message);
}
}
Here what contains of GetType
private string GetType(string file)
{
string type = string.Empty;
using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var request = XDocument.Load(stream);
var get_command = from r in request.Descendants("Transaction")
select new
{
Type = r.Element("Type").Value
};
foreach (var c in get_command)
{
type = c.Type;
}
}
return type;
}
You don't use your stream in code and while the stream is open you can not access the file in XDocument.Load(file)
private string GetType(string file)
{
string type = string.Empty;
var request = XDocument.Load(file);
var get_command = from r in request.Descendants("Transaction")
select new
{
Type = r.Element("Type").Value
};
foreach (var c in get_command)
{
type = c.Type;
}
return type;
}

Save email message as eml using C# in Lotus Notes

I need to export (save to) hard drive my Lotus Notes emails.
I figured out the way how to save attachments to HDD, but I can't figure out the way of how to save the whole email.
The code below shows how I export attachments. Can you suggest how can I modify it to save emails?
PS- I am new to programming.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domino;
using System.Collections;
namespace ExportLotusAttachments
{
class Class1
{
public void ScanForEmails()
{
String textBox1 = "c:\\1";
NotesSession session = new NotesSession();
session.Initialize("");
NotesDbDirectory dir = null;
dir = session.GetDbDirectory("");
NotesDatabase db = null;
db = dir.OpenMailDatabase();
NotesDatabase NDb = dir.OpenMailDatabase(); //Database connection
//ArrayList that will hold names of the folders
ArrayList LotusViews2 = new ArrayList();
foreach (NotesView V in NDb.Views)
{
if (V.IsFolder && !(V.Name.Equals("($All)")))
{
NotesView getS = V;
LotusViews2.Add(getS.Name);
}
}
foreach (String obj in LotusViews2)
{
NotesDocument NDoc;
NotesView nInboxDocs = NDb.GetView(obj);
NDoc = nInboxDocs.GetFirstDocument();
String pAttachment;
while (NDoc != null)
{
if (NDoc.HasEmbedded && NDoc.HasItem("$File"))
{
object[] AllDocItems = (object[])NDoc.Items;
foreach (object CurItem in AllDocItems)
{
NotesItem nItem = (NotesItem)CurItem;
if (IT_TYPE.ATTACHMENT == nItem.type)
{
String path = textBox1;
pAttachment = ((object[])nItem.Values)[0].ToString();
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(textBox1);
}
try
{
NDoc.GetAttachment(pAttachment).ExtractFile(#path + pAttachment);
}
catch { }
}
}
}
NDoc = nInboxDocs.GetNextDocument(NDoc);
}
}
}
}
}
This post by Bob Babalan explains how to export lotus documents using Java. The same principle should work in C# or VB. The document is cnverted into MIME and written to the disk.
Or in version 8.5.3 (I think it started witn 8.5.1) you can just drag and drop it from the mail file to the file system.
I know it is a bit late, but this is, what I did. (Based on Bob Babalan)
Bobs Solution helped me alot to understand NotesMIMEEntities, but in his solution, he only traversed the MIME-Tree to the second "layer". This will traverse multiple layers.
public static void GetMIME(StreamWriter writer, NotesMIMEEntity mimeEntity)
{
try
{
string contentType = null;
string headers = null;
string content = null;
string preamble = null;
MIME_ENCODING encoding;
contentType = mimeEntity.ContentType;
headers = mimeEntity.Headers;
encoding = mimeEntity.Encoding;
// message envelope. If no MIME-Version header, add one
if (!headers.Contains("MIME-Version:"))
writer.WriteLine("MIME-Version: 1.0");
writer.WriteLine(headers);
// for multipart, usually no main-msg content...
content = mimeEntity.ContentAsText;
if (content != null && content.Trim().Length > 0)
writer.WriteLine(content);
writer.Flush();
if (contentType.StartsWith("multipart"))
{
preamble = mimeEntity.Preamble;
NotesMIMEEntity mimeChild = mimeEntity.GetFirstChildEntity();
while (mimeChild != null)
{
GetMimeChild(writer, mimeChild);
mimeChild = mimeChild.GetNextSibling();
}
}
writer.WriteLine(mimeEntity.BoundaryEnd);
writer.Flush();
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
private void GetMimeChild(StreamWriter writer, NotesMIMEEntity mimeEntity)
{
string contentType = null;
string headers = null;
string content = null;
string preamble = null;
MIME_ENCODING encoding;
contentType = mimeEntity.ContentType;
headers = mimeEntity.Headers;
encoding = mimeEntity.Encoding;
if (encoding == MIME_ENCODING.ENC_IDENTITY_BINARY)
{
mimeEntity.EncodeContent(MIME_ENCODING.ENC_BASE64);
headers = mimeEntity.Headers;
}
preamble = mimeEntity.Preamble;
writer.Write(mimeEntity.BoundaryStart);
if (!content.EndsWith("\n"))
writer.WriteLine("");
writer.WriteLine(headers);
writer.WriteLine();
writer.Write(mimeEntity.ContentAsText);
if (contentType.StartsWith("multipart"))
{
preamble = mimeEntity.Preamble;
NotesMIMEEntity mimeChild = mimeEntity.GetFirstChildEntity();
while (mimeChild != null)
{
GetMimeChild(writer, mimeChild);
mimeChild = mimeChild.GetNextSibling();
}
}
writer.Write(mimeEntity.BoundaryEnd);
writer.Flush();
}
I would call this methods like this, to save the EML-File to a given path.
using (FileStream fs = new FileStream (path,FileMode.Create,FileAccess.ReadWrite,FileShare.None))
{
using (StreamWriter writer = new StreamWriter(fs))
{
NotesMimeEntity mimeEntity = notesDocument.GetMIMEEntity();
if (mimeEntity != null)
GetMIME(writer, mimeEntity);
}
}

Categories