Is there a simpler way to do this? I am sincerely concerned that this LinqPad doodle might be too verbose:
var xml = #"
<root attr1=""attribute one"" attr2=""attribute two"">
<title>this is the root</title>
<xhtml>
<div id=""wrapper"">
<p style=""first""><em>hello</em> world!</p>
</div>
</xhtml>
</root>
";
var xDoc = XDocument.Parse(xml);
Func<XNode, string> getXhtml = node =>
{
var s = string.Empty;
StringWriter wr = null;
try
{
wr = new StringWriter();
using(var jsonWriter = new JsonTextWriter(wr))
{
jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
new JsonSerializer().Serialize(jsonWriter, node.ToString());
}
s = wr.ToString();
}
finally
{
if(wr != null) wr.Dispose();
}
return s;
};
var escaped_xhtml = getXhtml(xDoc.Root.Element("xhtml").Element("div"));
escaped_xhtml.Dump("escaped xhtml");
var placeholder = "#rx-xhtml";
xDoc.Root.Element("xhtml").Value = placeholder;
var json = JsonConvert.SerializeXNode(xDoc.Root, Newtonsoft.Json.Formatting.Indented);
var json_final =json
.Replace(string.Format(#"""{0}""",placeholder), escaped_xhtml);
json_final.Dump("json with escaped xhtml");
var jDoc = JObject.Parse(json_final);
escaped_xhtml = (string)jDoc["root"]["xhtml"];
escaped_xhtml.Dump("decoded xhtml");
It may be reasonable to assume that JSON.NET already has, say, the equivalent of my getXhtml() routine. JSON.NET has so many great features I am concerned that I might be missing out.
Is this what you want? It produces the same result for json_final:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Extract the "div" element.
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
// Convert the remainder to a JObject.
var jDoc = JObject.FromObject(xDoc.Root, JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() } }));
// Store the Div element as a string literal.
jDoc["root"]["xhtml"] = div.ToString();
// Stringify the JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(jDoc, new JsonSerializerSettings { Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });
It eliminates the string replacement and the getXhtml delegate. Note that StringEscapeHandling applies during the final conversion to string, not to intermediate conversions to Joken (where string literals are not escaped).
Even simpler still, replace the <Div> element with a corresponding XML string literal before converting to JSON:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Replace the DIV element with its XML string literal value
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
xDoc.Root.Element("xhtml").Value = div.ToString();
// Convert to JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(xDoc, new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() }, Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });
Related
I would like to create dynamic PDF documents using HTML and dynamic images. My code works fine with standard HTML and full paths for the images, but when I try to embed the image inline in the document I get the error
Exception Details: System.IO.IOException: The document has no pages.
Is there a way to embed the images without an HTTP call per image? I don't want that because I think it will cause scalability issues and the images are sensitive.
Here is my code that gives the IOException:
public ActionResult MakePdf()
{
string html = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE html
PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
<head>
<title>Minimal XHTML 1.0 Document with W3C DTD</title>
</head>
<body><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD4AAABQCAMAAAB24TZcAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGAUExURdSmeJp2SHlbQIRoSUg2J499a8KebqeHZuGufBEVJPz7+3NWPVxGMduwhPXEktnX1mtROLq7t5WDc2VMNv3LmKB8TMSidMbFxLGlmXlhSMSddpJUL+y8i3VlVqedlOzr6gUIF2lXRLCLY4ZyXLyYaYhtUYiJhJFyU1dBLLiVZnlwZrWRY/Hx8b+2rbySaJh9YqeooDw4NygnK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EBe9Xm/8KEQs67hShMmgIRsNylFuFe9UL1IGHXHNAtr77ZYN7htNB8LxJmCnyaBZULpJ6/g4ZZQCX83FAS1u3675xnTaX/GKFdLl+gIaDZeFpU78rS9oDnzZEmHstqPJKc9n90LJPThyBUZIVRtMv8Q1v9Xx8bzxigddWo1t7yZ//zgSCwRiK6CO0PUD2OR4hMnhHfiPtYiJr4a8Jj4MbHNe7UC4RtTfc5wsd+DD6RbxxTZ8chtkrcJGIlqX41GqTVzFp3wmfmCNi5rNT74Z3nwHi2BjZW11AtdzgvxIfSBl4l/Klzr+bfLvzSNYA1u9xTfmz8f4lLmA5HWfgV8eTa7BEohxox1xeZ1F5Ef4fTrYnL4oGjb7QZ3JVgk2W4KJPMZvmWbo9KWJ27QsXKHm3DkhJT/Gs6z55lo0abV5wCSL5txL/CMa4PYPUXN+5qwTj68aXwa5MP4Efj/VDA4TW3BV3PQMp7Wlgnfg555mcPFO8RbXMbXv8Oh6pG3J7IRM8bq3Q/zKLFqUQ3GteNYvbepG1XG57O0Qt9Hmd1bOKC1qbZH/zbK78FWzYMJ2aZoXPq7kr8ZvORr+iUSjJzQb/Gpa5l8BBgBZTppAyfsf0wAAAABJRU5ErkJggg==' width='62' height='80' style='float: left; margin-right: 28px;' /></body></html>";
var bytes = Encoding.UTF8.GetBytes(html);
using (MemoryStream input = new MemoryStream(bytes))
{
MemoryStream output = new MemoryStream();
using (Document document = new Document(PageSize.LETTER, 50, 50, 50, 50))
{
using (PdfWriter writer = PdfWriter.GetInstance(document, output))
{
writer.CloseStream = false;
document.Open();
XMLWorkerHelper xmlWorker = XMLWorkerHelper.GetInstance();
xmlWorker.ParseXHtml(writer, document, input, null);
document.Close();
output.Position = 0;
return new FileStreamResult(output, "application/pdf");
}
}
}
}
We need to write our own ImageTagProcessor to support processing of base 64 images:
public class CustomImageTagProcessor : iTextSharp.tool.xml.html.Image
{
public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent)
{
IDictionary<string, string> attributes = tag.Attributes;
string src;
if (!attributes.TryGetValue(HTML.Attribute.SRC, out src))
return new List<IElement>(1);
if (string.IsNullOrEmpty(src))
return new List<IElement>(1);
if (src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase))
{
// data:[<MIME-type>][;charset=<encoding>][;base64],<data>
var base64Data = src.Substring(src.IndexOf(",") + 1);
var imagedata = Convert.FromBase64String(base64Data);
var image = iTextSharp.text.Image.GetInstance(imagedata);
var list = new List<IElement>();
var htmlPipelineContext = GetHtmlPipelineContext(ctx);
list.Add(GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers().Apply(image, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext));
return list;
}
else
{
return base.End(ctx, tag, currentContent);
}
}
}
Then we can inject this new processor into the HtmlPipelineContext:
using (var doc = new Document(PageSize.A4))
{
var writer = PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));
doc.Open();
var html = #"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD4AAABQCAMAAAB24TZcAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGAUExURdSmeJp2SHlbQIRoSUg2J499a8KebqeHZuGufBEVJPz7+3NWPVxGMduwhPXEktnX1mtROLq7t5WDc2VMNv3LmKB8TMSidMbFxLGlmXlhSMSddpJUL+y8i3VlVqedlOzr6gUIF2lXRLCLY4ZyXLyYaYhtUYiJhJFyU1dBLLiVZnlwZrWRY/Hx8b+2rbySaJh9YqeooDw4NygnKvvJlpyblzksIUhGRryYckc7MPjGlKODX5x8VVA8K+azgM3FvDInHK2JW2ZbUOHh4Xt2cFpaWKeAUM6kel1RRJmUjo5vSrWzrJJ1WFhLQCQmMuK1iJiMgmthWPPCkOm3hEtBOunm5LCNXnJtZquEXmNkYvG+i7Ctq+y5hrWRbKqSeaN/WqmFVYFgQh8aGOa4isWkd8mcby4vONDNy0AwI5h2U19JM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UC4RtTfc5wsd+DD6RbxxTZ8chtkrcJGIlqX41GqTVzFp3wmfmCNi5rNT74Z3nwHi2BjZW11AtdzgvxIfSBl4l/Klzr+bfLvzSNYA1u9xTfmz8f4lLmA5HWfgV8eTa7BEohxox1xeZ1F5Ef4fTrYnL4oGjb7QZ3JVgk2W4KJPMZvmWbo9KWJ27QsXKHm3DkhJT/Gs6z55lo0abV5wCSL5txL/CMa4PYPUXN+5qwTj68aXwa5MP4Efj/VDA4TW3BV3PQMp7Wlgnfg555mcPFO8RbXMbXv8Oh6pG3J7IRM8bq3Q/zKLFqUQ3GteNYvbepG1XG57O0Qt9Hmd1bOKC1qbZH/zbK78FWzYMJ2aZoXPq7kr8ZvORr+iUSjJzQb/Gpa5l8BBgBZTppAyfsf0wAAAABJRU5ErkJggg==' width='62' height='80' style='float: left; margin-right: 28px;' />";
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor
CssFilesImpl cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
var cssResolver = new StyleAttrCSSResolver(cssFiles);
cssResolver.AddCss(#"code { padding: 2px 4px; }", "utf-8", true);
var charset = Encoding.UTF8;
var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
var worker = new XMLWorker(pipeline, true);
var xmlParser = new XMLParser(true, worker, charset);
xmlParser.Parse(new StringReader(html));
}
Process.Start("test.pdf");
string originalFile = "Original1.pdf";
string copyOfOriginal = "Re-copia.pdf";
byte[] bytes = Convert.FromBase64String(archivo);
System.IO.FileStream stream = new FileStream(originalFile, FileMode.CreateNew);
System.IO.BinaryWriter writer = new BinaryWriter(stream);
writer.Write(bytes, 0, bytes.Length);
writer.Close();
PdfReader reader1 = new PdfReader(originalFile);
using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write
// Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
// Loop through each Page
for (int i = pageCount; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetUnderContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
PdfGState gState = new PdfGState();
cb.SetGState(gState);
string codbartest = codBarras;
BarcodePDF417 bcpdf417 = new BarcodePDF417();
//Asigna el código de barras en base64 a la propiedad text del objeto..
bcpdf417.Text = ASCIIEncoding.ASCII.GetBytes(codbartest);
Image imgpdf417 = bcpdf417.GetImage();
imgpdf417.SetAbsolutePosition(50, 50);
imgpdf417.ScalePercent(100);
cb.AddImage(imgpdf417);
// Close the layer
cb.EndLayer();
}[enter image description here][1]
I am trying to add an element in existing isolated folder in xml
code:
public void writeToXML(List<AppTile> appList)
{
// Write to the Isolated Storage
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!ISF.FileExists("config.xml"))
{
using (IsolatedStorageFileStream stream = ISF.OpenFile("config.xml", FileMode.CreateNew))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AppTile>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
serializer.Serialize(xmlWriter, appList);
}
stream.Close();
}
}
else
{
string tileName = null;
string url = null;
string key = null;
byte [] tilePic = null;
XDocument loadedData;
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
tilePic = app.TilePic;
// tilePic = Encoding.UTF8.GetString(app.TilePic,0,app.TilePic.Length);
// tilePic = Encoding.Unicode.GetString(app.TilePic,0,app.TilePic.Length);
// var writer = new BinaryWriter(tilePic);
}
using (Stream stream = ISF.OpenFile("config.xml", FileMode.Open, FileAccess.ReadWrite))
{
loadedData = XDocument.Load(stream);
var RootNode = new XElement("AppTile");
RootNode.Add(new XElement("TileName", tileName));
RootNode.Add(new XElement("Key", key));
RootNode.Add(new XElement("Url", url));
RootNode.Add(new XElement("TilePic", tilePic));
// Find Root Element And Descedents and Append New Node After That
var root = loadedData.Element("ArrayOfAppTile");
var rows = root.Descendants("AppTile");
var lastRow = rows.Last();
lastRow.AddAfterSelf(RootNode);
}
// Save To ISOconfig.xml File
using (IsolatedStorageFileStream newStream = new IsolatedStorageFileStream("config.xml", FileMode.Create, ISF))
{
loadedData.Save(newStream);
newStream.Close();
}
}
}
}
}
while reading from xml i am using xmlWriter and deserialize it to get List
when ever i am trying to acces the tilePic of AppTile type i am getting error :The component cannot be found. with the following code::
Image img = new Image();
MemoryStream imgStream = new MemoryStream(NewApp.TilePic);//NewApp is AppTile type
BitmapImage imgSource = new BitmapImage();
imgSource.SetSource(imgStream);//here i get error
img.Source = imgSource;
Its most likely with the TilePic i am saving is not formatted correctly to be retrieved.
Please Help!!
Why don't you use the SaveJpeg extension methodoogy in creating the byte array?
This one might help you!
Windows Phone - byte array to BitmapImage converter throws exception
solved the issue:
while saving the byte array it is encoded to some format not recognizable while reading,So what i have done is saved it as a string.So the updated code is:
else
{
string tileName = null;
string url = null;
string key = null;
string tilePicString = null;
XDocument loadedData;
System.Windows.Media.Imaging.BitmapImage imgSource = new System.Windows.Media.Imaging.BitmapImage();
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
//changed here
tilePicString = System.Convert.ToBase64String(app.TilePic);
}
//same code as above
I have a JSON object that I want to store in a database. The JSON is generated by an User Control.
The JSON object:
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
What is the best way to record a JSON object in the database using GeneXus?
Edit:
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
You can use a LongVarChar attribute to store the JSON, but you'll need to convert the JavaScript object to String first.
I have that code:
private function handleFlashVarsXmlLoaded(event:Event) : void
{
var secondsplit:String = null;
var item:Array = null;
var string:* = XML(String(event.target.data));
var notsplited:* = string.vars_CDATA; //what is .vars_CDATA?
var splitted:* = notsplitted.split("&");
var datacontainer:Object = {};
var index:Number = 0;
item = secondsplit.split("=");
datacontainer[item[0]] = item[1];
this.parseFlashVars(datacontainer); // go next
return;
}
That function is loaded when URLLoader is loaded.
I think that this function parse a XML file to string(fe. param1=arg1¶m2=arg2), then split it by "&" and then by "=" and add data to datacontainer by
datacontainer["param1"] = "arg1"
But how should the XML file look like and what is string.vars_CDATA
I think, vars_CDATA is just a name of XML field, becourse variable named "string" is contains whole XML. So var "notsplited" contains a String-typed data of this field (I think so, becourse of the line "var splitted:* = notsplitted.split("&");", which splits String to Array).
I have the following two routines in Flash Builder:
public function getData():void {
httpService = new HTTPService();
httpService.url = "https://mongolab.com/api/1/databases/xxx/collections/system.users/?apiKey=xxx";
httpService.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
httpService.addEventListener(ResultEvent.RESULT, resultHandler);
httpService.send();
}
public function resultHandler(event:ResultEvent):void {
var rawData:String = String(event.result);
var arr:Array = JSON.decode(rawData) as Array;
Debug.log(rawData);
Debug.log(arr);
httpService.removeEventListener(ResultEvent.RESULT, resultHandler);
}
rawData is displayed as JSON data but arr is displayed as [object Object] rather than an array.
What am I doing wrong?
this
var jsonStr:String = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S"},"GlossSee": "markup"}}';
will be parsed and JSON.decode returns an Object and you can access the attributes like this:
var obj:* = JSON.decode(jsonStr);
trace(obj.glossary);
this
var jsonStr:String = '[{"title":"asd"},{"title":"asd"},{"title":"asd"},{"title":"asd"}]';
will be parsed and returns an Array (which if you trace it, will return [object Object]).
so if you don't know what data is returned you could just check if
var result:* = JSON.decode(jsonStr);
if (result.length != undefined) {
// array
var arr:Array = result as Array;
}
else {
// object
var obj:Object = result as Object;
}
a try/catch around decode would also be good, because you don't know if the jsonStr is well-formed...
cheers