Create HTML webpage programmatically in C# - c#

I was wondering: is there a way to create HTML files programmatically in C# as you can do with XML? Mine is a console application, so maybe some of the options are not available. Basically, I would like to do something smarter than just building a big string.
Possible scenario:
Instead of writing:
string html="<html><head>Blah</head><body>{0}</html>", myotherstring
I would like to work as in XML
XmlTextWriter w = new XmlTextWriter(xml_file_path + xml_file_name,
System.Text.Encoding.UTF8);
w.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
// construct xml
XmlElement root = xmlDoc.CreateElement("element");
...
xmlDoc.Save(w);
w.Close();
Apologies for the naive question.

Don't forget: You can generate XHTML just as easily as plain XML using the XmlTextWriter approach.

You could use NVelocity. It is a .Net port of the Java Velocity templating system. The API will not be similar to XmlWriter. Instead, you'll write a text file in a simple scripting language, put your objects into a 'context' and then merge the template and the context to generate the HTML file.
NVelocity

You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.
For example
html
[head
[title["Title of the page"]]
[meta_(
content: "text/html;charset=UTF-8",
http_equiv: "Content-Type")
]
[link_(href: "css/style.css", rel: "stylesheet", type: "text/css")]
[script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")]
]
[body
[div
[h1["Test Form to Test"]]
[form_(action: "post", id: "Form1")
[div
[label["Parameter"]]
[input_(type: "text", value: "Enter value")]
[input_(type: "submit", value: "Submit!")]
]
]
[div
[p["Textual description of the footer"]]
[a_(href: "http://google.com/")
[span["You can find us here"]]
]
[div["Another nested container"]]
]
]
];

I realise that this question is old, however the recent release of the ASP.Net MVC 3 Razor view engine now gives you the option to use this same Razor view engine to generate HTML for any purpose.
See Hosting Razor outside of ASP.Net for a guide on how to do this.

What I did a few months back, I had an asp.net file (aspx) saved as a template in a text file, whenever the user needed a new page, I would just copy that template into the user specified folder, change the extension .txt to .aspx, and programmatically add a few options depending on the user's needs. It was a simple page though. Of course, the more complex you go, the more complex the code will be.

Related

How can one syntax highlight and format GraphQL queries on an HTML page with C# on .NET Core / Blazor?

Basically what the title says; I would like to syntax highlight aka colourize the GraphQL queries like they do it in the "GraphiQL Explorer", and print it on an HTML page with .NET Core using C#. Im working with Blazor, so the pages are .razor.
See this screenshot:
And I also want to auto-format the queries so that the queries aren't on a single line, but with line-breaks and indentations as the button "prettify" does in the "GraphiQL explorer".
So here's a sample.
Convert this => {human(id: "1000") {name height(unit: FOOT)}}
to this =>
Edit:
Here's a blazorFiddle i created. BlazorFiddleSample
Basically format\indent the graphql queries in a component page like this converter does, freetooldev
This could be achieved using BlazorMonaco
https://github.com/serdarciplak/BlazorMonaco
the code setup should look like this for the options
private StandaloneEditorConstructionOptions EditorConstructionOptions(MonacoEditor editor)
{
return new StandaloneEditorConstructionOptions
{
AutomaticLayout = true,
Language = "graphql",
};
}
please follow the instructions to get it setup if this is something you want to try.
you can get more info on the use of Monaco Editor here:
https://microsoft.github.io/monaco-editor/

LSP hover text markdown links from C# not working

I'm working on a VSCode extension with an LSP (implemented in C#/Omnisharp). I've implemented my language hover provider in the LSP and it's working fine. However, I want to add a clickable [vscode] command link to the hover. I've done this before using markdown in extension Typescript code like [Label](command:some-command), but it's not working from the LSP C# code. From there it just displays flat text as Label, but not as a clickable URI link. If the Uri is a regular https link it works, but not if it's a vscode Uri. Anyone know the magic to enable vscode command links in markdown from LSP C# code?
You need to set the markdown content isTrusted flag to get links to work. For a language extension server you need edit the LanguageClientOptions in the client's typescript file.
let clientOptions: LanguageClientOptions = {
markdown: {
isTrusted: true,
},
}
let client = new LanguageClient('myClient', 'My Client', serverOptions, clientOptions);
It's described on their GitHub in this issue

How to fix Veracode error for InnerHtml

When running Veracode, it generated a bunch of errors pointing to the lines with InnerHtml.
For example, one of those lines is:
objUL.InnerHtml += "<tr><td></td><td class=\"libraryEdit\">" + HttpUtility.HtmlEncode(dtitems.Rows[currentitem]["content"].ToString()) + "</td>";
What do alternatives exist to fix it without using html server controls?
What exactly are you trying to do, and what exactly does Veracode say?
Most likely, it is complaining that you could end up with an arbitrary code injection vulnerability if the data passed into your InnerHtml is untrusted and could contain malicious JavaScript.
The tool may not complain if you manually construct the DOM elements using the JavaScript createElement function to build each DOM element manually.
I have faced this issue in my ASP.NET Webforms application. The fix to this is relatively simple.
Install HtmlSanitizationLibrary from NuGet Package Manager and refer this in your application.
At the code behind, please use the sanitizer class in the following way.
For example if the current code looks something like this,
YourHtmlElement.InnerHtml = "Your HTML content" ;
Then, replace this with the following:
string unsafeHtml = "Your HTML content";
YourHtmlElement.InnerHtml = Sanitizer.GetSafeHtml(unsafeHtml);
This fix will remove the Veracode vulnerability and make sure that the string gets rendered as HTML. Encoding the string at code behind will render it as 'un-encoded string' rather than RAW HTML as it is encoded before the render begins.

How to use ASP.NET MVC 3 and Stack Overflow's Markdown

I couldn't find any real sources for this. I'm building a site in ASP.NET MVC 3 and would like to take advantage of the Markdown editor that Stack Overflow uses. Does anybody have a good tutorial?
Where do you download the latest markdown? What language is it written in? Where would I start in integrating this into an MVC 3 project? Even after all the searching and reading I've done I'm still pretty confused.
I came across this site. But this seems outlandishly old and it would seem I would have to learn a little something about CGI and Perl which I have absolutely no experience with. A JavaScript/jQuery version would be splendid.
Update
I noticed this question is getting a fair amount of views so I decided to update it with some helpful references. I managed to get a Markdown editor working nicely on my website, and I wrote a few blogs about it.
MarkdownSharp and Encoded HTML
JQuery WMD Plugin
Finding and implementing the WMD editor
Stackoverflow open sourced their version of Markdown to the world. Its called MarkdownSharp and is written in C#.
Somebody wrote a HtmlHelper here:
http://blog.dantup.com/2011/03/an-asp-net-mvc-htmlhelper-extension-method-for-markdown-using-markdownsharp
If you are looking for how to implement a javascript editor there is an existing question:
Integrate Markitup text editor to ASP.NET MVC project
You are probably looking for MarkdownSharp
Open source C# implementation of Markdown processor, as featured on Stack Overflow.
To integrate it into an MVC app:
In a until or common controller, add the following action method
public ActionResult FormatMarkdown(string markdownText)
{
var md = new MarkdownSharp.Markdown();
string html = md.Transform(markdownText);
return Json(html, JsonRequestBehavior.AllowGet);
}
in your client side view:
#Html.TextArea("mdText", new { rows = 12, cols = 60 })
<div id="mdFormatted"></div>
and client side JS:
$(function () {
var mdText = $("#mdText");
var mdFormatted = $("#mdFormatted");
function setFormatted(data) {
mdFormatted.html(data);
};
mdText.toObservable("keypress")
.Throttle(200)
.Subscribe(function () {
$.getJSON("#VirtualPathUtility.ToAbsolute("~/Util/FormatMarkdown/")", {
markdownText: mdText.val()
}, setFormatted);
})
Download RxJs (from MSDN) and include the following two js files
<script src="#Url.Content("~/Scripts/rx.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/rx.jquery.js")" type="text/javascript"></script>
I know this question is old but I stumbled upon another solution markdowndeep which is very friendly with MVC
It can be installed through nuget PM> Install-Package MarkdownDeep.Full
Markdown in C#
// Create an instance of Markdown
var md = new MarkdownDeep.Markdown();
// Set options
md.ExtraMode = true;
md.SafeMode = false;
string output = md.Transform(input);
Editor
1.Copy the supplied js, css, png and htm files to your server. Depending where you place these files on your server, you might need to update the image urls in the css file.
2.Update your page to reference jQuery, the MarkdownDeep library and the MarkdownDeep css file (again, you might need to change the paths).
<link rel="stylesheet" href="mdd_styles.css"
<script type="text/javascript" src="jQuery-1.4.2.min.js">
<script type="text/javascript" src="MarkdownDeepLib.min.js">
NB: MarkdownDeepLib.min.js is a packaged, minified version of MarkdownDeep.js, MarkdownDeepEditor.js and MarkdownDeepEditorUI.js. For debugging, you can reference these three files instead.
3.Insert the Markdown editor into your page like this:
<div class="mdd_toolbar"></div>
<textarea cols=50 rows=10 class="mdd_editor"></textarea>
<div class="mdd_resizer"></div>
<div class="mdd_preview"></div>
Note: the associated divs are all optional and if missing, the plugin will create them. However... you might experience the page jumping around during load if you do this. ie: it's recommended to explicitly include them.
4.Called the MarkdownDeep jQuery plugin to convert the textarea to a MarkdownEditor
$("textarea.mdd_editor").MarkdownDeep({
help_location: "/Content/mdd_help.html",
disableTabHandling:true
});
Although I really like their product I am not affiliated with the makers of markdowndeep. I just thought they made a good product
This question is old, but I'm just leaving an answer here so that future readers can benefit from it.
I have used MarkdownSharp v1.13, It does NOT sanitize your html output. For example, if you type:
<script type="text/javascript">alert("Hacked");</script>
Into your input field, the output from MarkdownSharp contains the same script. Thus it exposes your website to XSS vulnerability.
Read this from Stackoverflow's article on PageDown:
It should be noted that Markdown is not safe as far as user-entered input goes. Pretty much anything is valid in Markdown, in particular something like <script>doEvil();</script>. This PageDown repository includes the two plugins that Stack Exchange uses to sanitize the user's input; see the description of Markdown.Sanitizer.js below.
So, from other point of view, maybe Markdown was not supposed to sanitize your input in the first place and MarkdownSharp implementation of it just conformed with those principles. I should mention that Stackoverflow does uses MarkdownSharp on their server side.

Persisting configuration items in .net

I have a set of configuration items I need to persist to a "human readable" file. These items are in a hierarchy:
Device 1
Name
Channel 1
Name
Size
...
Channel N
Name
...
Device M
Name
Channel 1
Each of these item could be stored in a Dictionary with a string Key and a value. They could also be in a structure/DTO.
I don't care about the format of the file as long as it's human readable. It could be XML or it could have something more like INI format
[Header]
Key=value
Key2=value
...
Is there a way to minimize the amount of boiler plate code I would need to write to manage storing/reading configuration items?
Should I just create Data Transfer Objects (DTO)/structures and mark them serializable (Does that generate bloated XML still human readable?)
Is there other suggestions?
Edit: Not that the software has to write as well as read the config. That leaves app.config out.
YAML for .NET
I think both the XmlSerializer and NetDataContractSerializer create human readable XML. I prefer the NetDataContractSerializer because it can do things the XmlSerializer cannot, but those extra features are probably more than you need for this. If you already have classes written for your configurations, one of these two are probably your shortest path to victory.
You could also write your configurations to the local app.config file, or a sub-config file using custom ConfigSections and the Configuration class.
If you serialize your structure to JSON you get a simpler representation of your object than in XML.
Here's a sample from James Netwon-King's JSON.Net site:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JavaScriptConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JavaScriptConvert.DeserializeObject<Product>(json);
You can read his blog and download JSON.Net here.
See the FileHelpers library. It's got tons of stuff for reading from and writing to a lot of different formats - and all you have to do is mark up your objects with attributes and call Save(). Sort of like ORM for flat files.
I suspect that what you'll want to use is an app.config file which contains your settings in an XML format that .NET will be able to load in using the System.Configuration namesapce.
More info here: Link
I've generally used the registry for storing configurations (I know, bad me!), but using System.Xml to read/write a lightweight XML file isn't hard. In fact, I've done just that recently for a plugin project that uses XML documents to communicate with its host as well as store its own persistent settings.
There is also the System.Configuration namespace, but I've not really dealt with it.
I'd use a data structure that can be serialized into XML - in fact, since I'm lazy, I'd use an ADO.NET DataSet, since it has a simple serialization format that you can produce without having to think terribly hard.
As far as making it human-readable goes: if it just has to be human-readable (and not human-modifiable, which I think is what you're describing here), I'd build an XSLT transform and use it to produce an HTML version of the configuration data whenever I wrote out the XML. That gives you as fine-grained control over the visual presentation of the data as you could possibly ask for.
My preference in this situation is to create a DataSet with DataTables for the configuration data arranged in a nice relational way - then use DataSet.WriteXML() to save it to a configuration file.
Then to load it again, you just use DataSet.ReadXML() and it's back in a nice query-able object.
This is an example config file that my app allows the user to edit in a Text Editor window:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--****************************************************************
Config File: FileToExcel_test.cfg
Author: Ron Savage
Date: 06/20/2008
Description:
File to test parsing a file into an Excel workbook.
Modification History:
Date Init Comment
06/20/2008 RS Created.
******************************************************************-->
<!--********************************************************************
Global Key Definitions
********************************************************************-->
<config key="sqlTimeout" value="1800"/>
<config key="emailSMTPServer" value="smtp-server.austin.rr.com"/>
<config key="LogFile" value="FiletoExcel_test_{yyyy}{mm}{hh}.log"/>
<config key="MaxEntries" value="1"/>
<!--********************************************************************
Delimiter Configurations
********************************************************************-->
<config key="pipe" value="|"/>
<!--********************************************************************
Source / Target Entries
********************************************************************-->
<config key="source_1" value="FILE, c:\inetpub\ftproot\filetoexcel.txt, pipe, , , , , "/>
<config key="target_1" value="XLS, REPLACE, c:\inetpub\ftproot\filetoexcel1.xls, , , , , , , ,c:\inetpub\ftproot\filetoexcel_template.xls, ,3"/>
<config key="notify_1" value="store_error, store_success"/>
</configuration>
When I load it into the DataSet, all the non-comment tags reside in a table named Config with fields Key & value. Very easy to search.

Categories

Resources