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.
Related
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/
I'm currently building a game, when I tried uploading it to AirConsole the game gives me a error in the preview.
Has anyone had this problem before?
"Uncaught ReferenceError: AirConsoleViewManager is not defined".
var airconsole = new AirConsole({ "orientation": "landscape", "device_motion": 10 });
var vm = null;
window.onload = start;
airconsole.onReady = function () {
//THE LINE UNDER CRASHES
vm = new AirConsoleViewManager(airconsole);
};
ReferenceError: AirConsoleViewManager is not defined
at AirConsole.airconsole.onReady (https://storage.googleapis.com/XXX.xxxxxxx.xxxx.cdn.airconsole.com/2018-05-24-16-33-25/controller.html:125:22)
at AirConsole.onPostMessage_ (https://www.airconsole.com/api/airconsole-latest.js:1053:8)
at https://www.airconsole.com/api/airconsole-latest.js:969:8
Thank you very much :)
I assume you got the information about AirConsoleViewManager from here (GitHub).
I can't tell for sure because you haven't linked the entire file, but you need to download the airconsole-view-manager.js and include that in your controller script.
The example from the previously linked GitHub example is kind of weird because it doesn't include the JS file in it. Most likely the reason for this is that they assume (which you should never do as a developer) people know it already.
EDIT: Actually, they do include the file but it's not done in JS file, it's in HTML file:
<script type="text/javascript" src="airconsole-view-manager.js"></script>
I do not know what the problem was, but after cleaning the build and transfering code over to another project, then uploading again it worked!
I am creating an application that interfaces with Google's Maps API v3. My current approach is using a WebBrowser control by WebBrowser.Navigate("Map.html"). This is working correctly at the moment; however, I am also aware of WebBrowser.InvokeScript(). I have seen this used to execute a javascript function, but I would like to have something like the following structure:
APICalls.js - Contains different functions that can be called, or even separated out into a file for each function if necessary.
MapInterface.cs
WebBrowser.InvokeScript("APICalls.js", args) - Or control the javascript variables directly.
I have seen the InvokeScript method used, but none of the examples gave any detail to the source of the function, so I'm not sure if it was calling it from an html file or js file. Is it possible to have a structure like this, or a similarly organized structure, rather than creating an html file with javascript in each one and using Navigate()?
Additionally, are there any easier ways to use Google Maps with WPF. I checked around, but all of the resources I found were at least 2-3 years old, which I believe is older than the newest version of the maps API.
I can't suggest a better way of using Google Maps API with WPF (although I'm sure it exists), but I can try to answer the rest of the question.
First, make sure to enable FEATURE_BROWSER_EMULATION for your WebBrowser app, so Google Maps API recognizes is it as modern HTML5-capable browser.
Then, navigate to your "Map.html" page and let it finish loading. Here's how it can be done using async/await (the code is for the WinForms version of WebBrowser control, but the concept remains the same).
You can have your APICalls.js as a separate local file, but you'd need to create and populate a <script> element for it from C#. You do it once for the session.
Example:
var scriptText = File.ReadAllText("APICalls.js");
dynamic htmlDocument = webBrowser.Document;
var script = htmlDocument.createElement("script");
script.type = "text/javascript";
script.appendChild(htmlDocument.createTextNode(scriptText));
htmlDocument.body.appendChild(script);
Then you can call functions from this script in a few different ways.
For example, your JavaScript entry point function in APICalls.js may look like this:
(function() {
window.callMeFromCsharp = function(arg1, arg2) {
window.alert(arg1 + ", " +arg2);
}
})();
Which you could call from C# like this:
webBrowser.InvokeScript("callMeFromCsharp", "Hello", "World!");
[UPDATE] If you're looking for a bit more modular or object-oriented approach, you can utilize the dynamic feature of C#. Example:
JavaScript:
(function() {
window.apiObject = function() {
return {
property: "I'm a property",
Method1: function(arg) { alert("I'm method 1, " + arg); },
Method2: function() { return "I'm method 2"; }
};
}
})();
C#:
dynamic apiObject = webBrowser.InvokeScript("apiObject");
string property = apiObject.property;
MessageBox.Show(property);
apiObject.Method1("Hello!");
MessageBox.Show(apiObject.Method2());
I have build a custom Html Helper extension as follows:
public static string DatePicker(this HtmlHelper helper, string name, string value)
{
return string.Format(#"<script type='text/javascript'>
$(document).ready(function(){{
$('#{0}').datepicker({{
changeMonth: true,
changeYear:true,
dateFormat: 'd-M-yy',
firstDay: 1, showButtonPanel:
true,
showWeek: true
}});
}});
</script>
<input type='text' name='{0}' id='{0}' value='{1}'>", name, value);
}
The problem is that this now requires the page to "include" the following:
<script src="/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.ui.datepicker.min.js" type="text/javascript"></script>
And a few other items. The questions are as follows:
Is there a serious processing
overhead if I were to include these
items in EVERY page (like in the
Site.Master for example) thus
negating the need for the HtmlHelper
to organise the "includes" -
considering there would end up being
about 20 includes for all the
different types of jQuery UI widgets
used throughout the site.
If the HtmlHelper sorts out the
"includes", it will add one every
time this DatePicker is used (often
there are two on a page) Does anyone
have a way of determining whether or
not the user has already rendered
the same type of control on the
page, thus not re-including the same
jquery libraries when multiple
instances of the DatePicker (for
example) are used?
Direct Answer
1) Yes 20 requests for scripts on each page will reduce performance for clients considerably - see Yahoo / Google's docs on web optimisation for more info
Browser Caching helps, but its so easy to do better.
2) Why roll your own solution to dependencies?
There are numerous excellent libraries out there that do this very well already - with advantages?
In depth :
Similar to the suggestion from #Mare , but with I think some decent advantages - I would recommend changing your approach slightly. Refactor !
Consider these core questions :
1) Why write HTML in .cs files?
=> much better to keep your HTML in aspx / ascx (or other view engine) files
check out editor and display templates e.g.
Brad Wilson's Intro to templates
i.e. comment from #admsteck above
2) why write Javascript in .cs files?
=> much better to keep your Javascript in .js files
3) Also note - Why use HtmlHelper extension methods when you are not using any of the state information from the HtmlHelper class?
=> For a simple solution why not instead just use a static helper class (not an extension of HtmlHelper) see this answer here
But mainly :
4) If you a concerned about performance, why not minify and combine all your scripts (and CSS while you're at it).
=>Then you can have a single little CSS file and a single JS file for your whole app.
However, 4) then leads to some further questions :
a) How do you debug combined + minified JS
b) How do you work effectively with combined + "minified" CSS?
c) To focus back in on your original request for a clean way to handle dependencies, how do you ensure its clear what code depends on what code, and how do you ensure code is requested only once when its needed?
I have found that this open source library Client Dependency Framework an excellent addition to my toolbox for MVC, when you debug you get individual files, when you run you get combined files (for massive performance gains in production).
It also provides an excellent way for your UI components to "register" their dependencies, so its clear to developers what is needed where, and so the correct js + the correct css gets down to the client (and only gets requested once) !
Maybe something of these code pieces will help you to get an idea or two about it:
private static readonly SortedList<int, string> _registeredScriptIncludes = new SortedList<int, string>();
public static void RegisterScriptInclude(this HtmlHelper htmlhelper, string script)
{
if (!_registeredScriptIncludes.ContainsValue(script))
{
_registeredScriptIncludes.Add(_registeredScriptIncludes.Count, script);
}
}
public static string RenderScript(this HtmlHelper htmlhelper, string script)
{
var scripts = new StringBuilder();
scripts.AppendLine("<script src='" + script + "' type='text/javascript'></script>");
return scripts.ToString();
}
public static string RenderScripts(this HtmlHelper htmlhelper)
{
var scripts = new StringBuilder();
scripts.AppendLine("<!-- Rendering registered script includes -->");
foreach (string script in _registeredScriptIncludes.Values)
{
scripts.AppendLine("<script src='" + script + "' type='text/javascript'></script>");
}
return scripts.ToString();
}
To answer number 2, you could do something like the following
<script type='text/javascript'>
if (typeof jQuery == 'undefined') // test to see if the jQuery function is defined
document.write("<script type='text/javascript' src='jquery.js'></script>");
</script>
Regarding:
1: no processing overhead at all, and no significant size overhead (as in: the files are normally loaded only first time by the browser). I normally would go this approach.
2: no idea, sorry ;) Someone else will pick that up, i think.
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.