Basecamp classic api: how to add a new line into comment body - c#

I use classic basecamp api, and I want to add a new line into comment body. I have been tried to use Envirovent.NewLine and CDATA, but basecamp remove it from result text.
Do anybody know how to do it? It is possible?

Getting a comment through a rest call reveals a div tag within the xml structure for a line break
Call
GET https://#{account_url}.basecamphq.com/comments/#{comment_id}.xml
Result
<?xml version="1.0" encoding="UTF-8" ?>
<comments count="1" type="array">
<comment>
...
<body>
<div> Comment-Text line ONE</div>
<div> Comment-Text line TWO</div>
</body>
...
</comment>
</comments>
However, posting xml to the API applying the same structure as above results in the following terrible looking comment in Basecamp Classic:
{"div"=>[" Comment-Text line ONE", " Comment-Text line TWO"]}
The CDATA tag does work but has to be implemented in the following manner:
<comment><![CDATA[
<body>
<div> Comment-Text line ONE</div>
<div> Comment-Text line TWO</div>
</body>
</comment>]]>
Or an example of feeding dynamic content with php
$comment_xml = "<comment><body><![CDATA[<div>Person: " . $first_name . " " . $last_name . "</div><div>Email: " . $email . "</div>]]></body></comment>";
<div> and <br /> tags will both work for new lines

I tried with \n , but it didn't worked..
table_config = [
{
'dbName': f'gomez_datalake_{env}_{team}_{dataset}_db',
'table': 'ConFac',
'partitionKey': 'DL_PERIODO',
'schema': [
['TIPO_DE_VALOR', 'STRING', 2, None,
"CÓDIGO DEL PARÁMETRO DE SISTEMA."
"EJEMPLOS:"
"UF: VALOR DE LA UF"
"IP: VALOR DEL IPC"
"MO: MONEDA"
"IV: VALOR DEL VA"
"UT: VALOR DEL UTM"],
['ORIGEN', 'STRING', 4, None, "IDENTIFICADOR DE USUARIO"]
]

Related

Xslt: escape XML nodes when producing HTML

I am using Microsoft's System.Xml.Xsl to create HTML. When transforming XML that contains escape sequences (e.g. <script>) into HTML, if the nodes are emitted as attributes, they are not escaped.
I would like to produce HTML where both attributes and nodes are escaped.
Xml sample:
<Contact>
<Name>hello <script>alert('!')</script></Name>
</Contact>
Xslt sample:
<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output method=""html"" indent=""yes"" doctype-system=""html"" />
<xsl:template match=""/"">
<span data-title=""{{ 'title': '{/Contact/Name}' }}"">
Name: <xsl:value-of select=""/Contact/Name""/>
Input: <input type=""text"" value=""{/Contact/Name}""/>
</span>
</xsl:template>
</xsl:stylesheet>
Sample code:
using System;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
public class Program
{
public static void Main()
{
var transform = new XslCompiledTransform();
var xml = #"<Contact><Name>hello <script>alert('!')</script></Name></Contact>";
var xslt = #"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output method=""html"" indent=""yes"" doctype-system=""html"" />
<xsl:template match=""/"">
<span data-title=""{{ 'title': '{/Contact/Name}' }}"">
Name: <xsl:value-of select=""/Contact/Name""/>
Input: <input type=""text"" value=""{/Contact/Name}""/>
</span>
</xsl:template></xsl:stylesheet>
";
transform.Load(XmlReader.Create(new StringReader(xslt)));
var settings = transform.OutputSettings.Clone();
using (var output = new MemoryStream())
using (var writer = XmlWriter.Create(output, settings))
{
var args = new System.Xml.Xsl.XsltArgumentList();
transform.Transform(XmlReader.Create(new StringReader(xml)), args, writer);
writer.Flush();
output.Position = 0;
Console.Write(new StreamReader(output).ReadToEnd());
}
}
}
Actual result (with a fiddle):
<!DOCTYPE html SYSTEM "html"><span data-title="{ 'title': 'hello <script>alert('!')</script>' }">
Name: hello <script>alert('!')</script>
Input: <input type="text" value="hello <script>alert('!')</script>"></span>
Expected / Desired result (with a fiddle):
<!DOCTYPE span SYSTEM "html">
<span data-title="{ 'title': 'hello <script>alert('!')</script>' }">
Name: hello <script>alert('!')</script>
Input: <input type="text" value="hello <script>alert('!')</script>" /></span>
Using XSLT 3 with xsl:output method="xhtml", possible with .NET framework using Saxon .NET 10.8 HE from Saxonica or with .NET 6/7 (Core) using SaxonCS 11 or 12 (commercial enterprise package) or using IKVM cross-compiled Saxon HE 11.4 Java, shown below, might give a result closer to your needs:
using net.sf.saxon.s9api;
using net.liberty_development.SaxonHE11s9apiExtensions;
using System.Reflection;
// force loading of updated xmlresolver (workaround until Saxon HE 11.5)
ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver"));
ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver_data"));
var processor = new Processor(false);
var xml = #"<Contact><Name>hello <script>alert('!')</script></Name></Contact>";
var xslt = #"<xsl:stylesheet version=""3.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output method=""xhtml"" indent=""yes"" html-version=""5.0"" doctype-system=""about:legacy-compat"" omit-xml-declaration=""yes""/>
<xsl:template match=""/"">
<span data-title=""{{ 'title': '{/Contact/Name}' }}"">
Name: <xsl:value-of select=""/Contact/Name""/>
Input: <input type=""text"" value=""{/Contact/Name}""/>
</span>
</xsl:template></xsl:stylesheet>
";
var xslt30Transformer = processor.newXsltCompiler().compile(xslt.AsSource()).load30();
var inputDoc = processor.newDocumentBuilder().build(xml.AsSource());
using var resultWriter = new StringWriter();
xslt30Transformer.applyTemplates(inputDoc, processor.NewSerializer(resultWriter));
var result = resultWriter.ToString();
Console.WriteLine(result);
Output is e.g.
<!DOCTYPE span
SYSTEM "about:legacy-compat">
<span data-title="{ 'title': 'hello <script>alert('!')</script>' }">
Name: hello <script>alert('!')</script>
Input: <input type="text" value="hello <script>alert('!')</script>"/></span>
Example project to show to use IKVM and Maven to include Saxon HE 11.4 Java is at https://github.com/martin-honnen/SaxonHE11NET7XHTMLOutputMethodExample1.

Handlebars.NET in .NET Core not filling in data in a simple example

I have a .NET 5 app that is trying to use Handlebars.NET. Right now, I'm just doing a very basic example to make sure it works, and it currently doesn't.
I have added the Nuget Handlebars.NET, but nothing else.
Here's my template:
<script id="handlebars-demo" type="text/x-handlebars-template">
<h1>Data Report for {{customer}}</h1>
<h2>Tenant: {{tenant}}</h2>
<p>
This is for testing.
</p>
</script>
Here's my context:
var context = "{ \"customer\" : \"mycustomer\", \"tenant\" : \"mytenant\" }";
Here's the C# code I'm using:
var template = Handlebars.Compile( html ); // contains the above template
string finalHtml = template( context );
The resulting text stored in finalHtml looks like this:
<script id="handlebars-demo" type="text/x-handlebars-template">
<h1>Data Report for </h1>
<h2>Tenant: </h2>
<p>
This is for testing.
</p>
</script>
My goal was for {{customer}} to be replaced with my mycustomer and {{template}} to be replaced with mytemplate, but they're being replaced with empty strings, it seems.
Can anyone see if I'm doing something wrong?
As mentioned in the comments, context should be an object and not a string.
var context = new {customer = "mycustomer", tenant = "mytenant"};
Please refer the documentation - https://github.com/Handlebars-Net/Handlebars.Net

Webdriver doesn't find any elements by id or class NoSuchElementException

I'm trying to get data from inside a div of a public website.
The Selenium WebDriver doesn't seem to find any elements. I tried to find elements with id and class even with a XPath but still didn't find anything.
I can see the html page code when looking at PageSource, this confirms the driver works. What am I doing wrong here? Selenium V2.53.1 // IEDriverServer Win32 v2.53.1
My code:
IWebDriver driver = new InternetExplorerDriver("C:\\Program Files\\SeleniumWebPagetester");
driver.Navigate().GoToUrl("D:\\test.html");
await Task.Delay(30000);
var src = driver.PageSource; //shows the html page -> works
var ds = driver.FindElement(By.XPath("//html//body")); //NoSuchElementException
var test = driver.FindElement(By.Id("aspnetForm")); //An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
var testy = driver.FindElement(By.Id("aspnetForm"), 30); //'OpenQA.Selenium.NoSuchElementException'
var tst = driver.FindElement(By.XPath("//*[#id=\"lx-home\"]"), 30); //'OpenQA.Selenium.NoSuchElementException'
driver.Quit();
Simple HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="#" id="aspnetForm" onsubmit="return false;">
<section id="lx-home" style="margin-bottom:50px;">
<div class="bigbanner">
<div class="splash mc">
<div class="bighead crb">LEAD DELIVERY MADE EASY</div>
</div>
</div>
</section>
</form>
</body>
</html>
Side note, my XPath works perfect with HtmlWeb:
string Url = "D:\\test.html";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
var element = doc.DocumentNode.SelectNodes("//*[#id=\"lx-home\"]"); //WORKS
It seems IE parses the local file in different way, so you cannot access DOM. Here are your options:
Use Chrome instead of IE
Keep using IE, move the file to C:\inetpub\wwwroot then change your code to open URL instead of localfile: driver.Navigate().GoToUrl("http://localhost/test.html");

Image is not shown on the view Using ASP.NET MVC

I am trying to show my data after json Deserialization on the web.Every data working perfectly except the Images. It shows only image sign on the web but now the actual images.My Code for controller class in where I deserialized Json object is as follows-
public ActionResult PlaceInformation(City objCityModel)
{
string name = objCityModel.Name;
ViewBag.Title = name;
var ReadJson = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/" + name + ".json"));
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
List<Poi> mycities = new List<Poi>();
foreach (var item in json.poi)
{
Poi obj = new Poi()
{
Name = item.Name,
Shorttext = item.Shorttext,
GeoCoordinates = item.GeoCoordinates,
Images = item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities = mycities;
return View();
}
Now in the view class I want to show every item from this json.But I am having error for images which I mentioned beside code. The error is:
An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Unexpected "foreach" keyword after "#" character. Once inside code, you do not need to prefix constructs like "foreach" with "#"
My code is -
#model CallListService.Models.City
#{
Layout = null;
}
#{
ViewBag.Title1 = "Show Data";
}
#foreach (var item in ViewBag.Cities)
{
<h2>#item.Name</h2>
<p>#item.Shorttext</p>
<p>#item.GeoCoordinates.Longitude</p>
<p>#item.GeoCoordinates.Latitude</p>
#foreach (var image in item.Images) //Parser Error
{
<img src=#image >
}
}
Again if I only write in this way it works but image is not shown, only img sign is shown.
<img src=#item.Images>
I am not finding any solution for this.
This is screenshot of web page
SourceCode:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PlaceInformation</title>
</head>
<body>
<div>
<h2>Nordertor</h2>
<p>The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.</p>
<p>9.43004861</p>
<p>54.79541778</p>
<img src="System.Collections.Generic.List`1[System.String]" />
<h2>Naval Academy M�rwik</h2>
<p>9.45944444</p>
<p>54.815</p>
<img src="System.Collections.Generic.List`1[System.String]" />
<h2>Flensburg Firth</h2>
</p>
<p>9.42901993</p>
<p>54.7959404</p>
<img src="System.Collections.Generic.List`1[System.String]" />
</div>
</body>
</html>
I am using following json file to get all data
{
"poi":[
{
"Name": "Nordertor",
"Shorttext": "The Nordertor is an old tows used as a symbol for Flensburg.",
"GeoCoordinates": {
"Longitude": 9.43004861,
"Latitude": 54.79541778
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG/266px-Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG"
]
},
{
"Name": "Naval Academy Mürwik",
"Shorttext": "The Naval Academy Mürwik is the main training e..",
"GeoCoordinates": {
"Longitude": 9.45944444,
"Latitude": 54.815
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/MSM-hauptgebaeude.jpg/400px-MSM-hauptgebaeude.jpg"
]
},
{
"Name": "Flensburg Firth",
"Shorttext": "Flensburg Firth or Flensborg Fjordg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
"GeoCoordinates": {
"Longitude": 9.42901993,
"Latitude": 54.7959404
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Flensborg_Fjord_ved_bockholmwik.jpg/400px-Flensborg_Fjord_ved_bockholmwik.jpg"
]
}
]
}
Image tag will always expect path for that image
<img src="./images/name.jpg" />
or
<img src="http:/wwww.sitename.com/images/name.jpg" />
what does you Image contain image path or image byte?
if it contain image byte then it has to be rendered separately by creating an intermediate page
Change the inner loop to:
foreach (var image in item.Images) //without the `#`
{
<img src="#image" /> //with " and />
}
This should work if the specified file exists. (if it doesn't work, show the full error + html :-)

How to parse Json in C# Web as open Source

net and i just want to read a Json and want to update or add the nodes in JSON. I have used Angular and PHP for this and i was able to read and write the file easily. But My server is now IIS, So i want to parse JSON file on C# and want to change the values in it.
I googled a lot and found a lot of solution for JSON.NET or Newtonsoft.Json. I have only one index.aspx page, where i am successfully able to read the json file as below
string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
Response.Write(json);
And this is printing JSON text in web easily. But i am not able to parse it properly. I am writing code in Notepad++, as i don't have Visual Studio and don't want to install. I heard that .net code is open source now, So i tried this from Notepad++. Now please let me know, how to Parse JSON without using Visual Studio?
My code in more detail is as below
index.aspx
<%# Page Language="C#" %>
<!Doctype html>
<html>
<body>
<form action="index.aspx" method="post" enctype="multipart/form-data" runat="server">
<input type="text" id="empname" name="empname" placeholder="Enter Full Name"/>
<p><button id="addBtn" class="btn btn-success" onclick='return addEmployee()' type="submit">Add</button> <button id="removeBtn" class="btn btn-success" onclick='removeEmployee()'>Remove</button></p>
</form>
<%
string ename = Request.Form["empname"];
string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
Response.Write(json);
//Here i want to parse JSON file
%>
</body>
</html>
Javascript
function addEmployee()
{
if($("#empname").val() == "")
{
alert("Please type Name.");
$("#empname").focus();
return false;
}
return true;
}
JSON
[
{
"ID": "ID01",
"Name": "First One"
},
{
"ID": "ID02",
"Name": "Second One"
}
]
Remember i am writing code in Notepad++, So please let me know accordingly. Thanks in advance.
JavaScriptSerializer has been deprecated and Microsoft recommends using Json.NET.
Download Json.NET here.
In your aspx page link to Json.NET:
<%# Assembly Name="Newtonsoft.Json" %>
<%# Import namespace="Newtonsoft.Json" %>
Make a class for Employee:
public class Employee
{
public string ID { get; set; }
public string Name { get; set; }
}
Add a reference to Json.NET:
using Newtonsoft.Json;
Deserialize your Json from disk:
List<Employee> list = JsonConvert.DeserializeObject<List<Employee>>(json);
// ...
list.Add(employee);
// deserialize + save
string json = JsonConvert.SerializeObject(list);

Categories