MVC6 new minification and bundling with Bower/NPM - c#

I started getting up to date with the ASP.NET 5 and MVC 6, and I see a lot of internet posts about Bower VS NPM.
The default started MVC template however uses both, is this required for the taskrunner (gulp) to work or is there another reason?
Second question is about the resource path, in MVC < 6 you could declare a relative path to research the minified/bundled js/css. This way each MVC View would have its own path to its own specific js/css. How can I do this with gulp?
In MVC < 6 the js/css would NOT minify when debug enabled (as default setting), so it remains readable. I see the option to use an if-like statement on the environment variable like
environment names="Development">script path
and another one for production in the view. This seems very cumbersome, is there a simple solution for not minifying in debug instead of having to list all paths twice (one minified and one not)?

Have one version of watch minify your js files and one that doesn't. Either way all of your project paths can just point to the built js file to prevent having to switch back and forth for dev or prod. You would need to break the minify stuff out of the 'scripts' task below and create a task that just does that.
//Concatenate & Minify JS
gulp.task('minscripts', function () {
return gulp.src(config.alljs, { base: 'public/' })
.pipe($.concat('all.js'))
.pipe(gulp.dest('_build'))
.pipe($.rename('all.min.js'))
.pipe($.uglify())
.pipe(gulp.dest(config.build));
});
gulp.task('scripts', function () {
return gulp.src(config.alljs, { base: 'public/' })
.pipe($.concat('all.js'))
.pipe(gulp.dest('_build'))
.pipe($.rename('all.min.js'))
.pipe(gulp.dest(config.build));
});
gulp.task('watchWith', function () {
gulp.watch('public/app/views/*.js', ['lint', 'minscripts']); //<- runs 'scripts' here
gulp.watch('public/css/*.less', ['less']);
});
gulp.task('watchWithout', function () {
gulp.watch('public/app/views/*.js', ['lint', 'scripts']);
gulp.watch('public/css/*.less', ['less']);
});

Related

Reading base path from web.config

I have a web application created in MVC5/C#
The app uses jscript to call actions from a controller for certain instances. The problem I am having is that the application is nested deeper on IIS than on my local server.
Local:
var urlForModesl = "/ICS_Requisitions/Details";
IIS
var urlForModesl = "../ICS_Requisitions/Details";
Is there anyway I can grab the base path dynamically . . maybe from web.config or something? So that I don't have to keep switching back and forth. It's making testing a bit cumbersome, as there are similar situations throughout the application.
Have you tried Bundling of Js. If not follow this
// create an object of ScriptBundle and
// specify bundle name (as virtual path) as constructor parameter
ScriptBundle scriptBndl = new ScriptBundle("~/bundles/bootstrap");
//use Include() method to add all the script files with their paths
scriptBndl.Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"
);
//Add the bundle into BundleCollection
bundles.Add(scriptBndl);
BundleTable.EnableOptimizations = true;
Find more details on this link
https://www.tutorialsteacher.com/mvc/scriptbundle-mvc

AirConsole View Manager is not defined after uploading for testing

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!

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.

ASP.NET MVC Html Helper Extensions and Rendering Their Required "include"s

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.

Can I run a ASPX and grep the result without making HTTP request?

How can I just make a function call, without URL, and without HTTP, to a simple ASP.NET file, and capture the byte stream it generated?
More background information,
I need a some kind of template can put a little logic inside, to render some INI like text files. I give up those libraries ported from Java and come up a solution of using ASP.NET for template engine. (I am NOT using it to build a website, not even a HTML.)
I have written a ASP.NET page (no WebForm, no MVC), which accept a XML POST, and it generate a long text file based on a set of simple but not too simple rules.
I generate the XML from DB objects, submit to the ASP page, grep the result and it works very well. However, the problem is that we want to use as a library, using by a WCF. Because of this, I failed to use a relative path and I have to store the URL of the ASP somewhere in the configuration, which I do not want to.
It will be hosted on a IIS server, but not called (at least not directly) from any frontend ASP, and will never called from end user.
PS. I was originally looking for a simple template engine for C#, but they are too old and not maintenance anymore, poor documentation, missing integrated editor/debugger, too simple, and the they might speak different languages.
PPS. I've also thought about T4, but it does not have a editor nor debugger in VS 2008.
You can run an ASPX page without IIS, without an HTTP message, if you build a host for the ASPNET runtime.
Example:
public class MyAspNetHost : System.MarshalByRefObject
{
public void ProcessRequest(string page)
{
var request = new System.Web.Hosting.SimpleWorkerRequest
(page, // the page being requested
null, // query - none in this case
System.Console.Out // output - any TextWriter will do
);
// this will emit the page output to Console.Out
System.Web.HttpRuntime.ProcessRequest(request);
}
public AppDomain GetAppDomain()
{
return System.Threading.Thread.GetDomain();
}
}
public class Example
{
public void Run(IEnumerable<String> pages)
{
// ASPNET looks for assemblies - including the assembbly
// that contains any custom ASPNET host - in the bin\
// subdirectory of the physical directory that backs the
// ASPNET Host. Because we are going to use the current
// working directory as the physical backing directory for
// the ASPNET host, we need to ensure there's a bin
// subdirectory present.
bool cleanBin = false;
if (!Directory.Exists("bin"))
{
cleanBin = true;
Directory.CreateDirectory("bin");
}
// Now, ensure that the assembly containing the custom host is
// present in that bin directory. The assembly containing the
// custom host is actually *this* assembly.
var a = System.Reflection.Assembly.GetExecutingAssembly();
string destfile= Path.Combine("bin", Path.GetFileName(a.Location));
File.Copy(a.Location, destfile, true);
host =
(MyAspNetHost) System.Web.Hosting.ApplicationHost.CreateApplicationHost
( typeof(MyAspNetHost),
"/foo", // virtual dir - can be anything
System.IO.Directory.GetCurrentDirectory() // physical dir
);
// process each page
foreach (string page in pages)
host.ProcessRequest(page);
}
}
If you want to clean up that bin directory, you have to get the AppDomain to unload first. You can do that, like this:
private ManualResetEvent aspNetHostIsUnloaded;
private void HostedDomainHasBeenUnloaded(object source, System.EventArgs e)
{
// cannot clean bin dir here. The AppDomain is not yet gone.
aspNetHostIsUnloaded.Set();
}
private Run(IEnumerable<String> pages)
{
try
{
....code from above ....
}
finally
{
if (host!= null)
{
aspNetHostIsUnloaded = new ManualResetEvent(false);
host.GetAppDomain().DomainUnload += this.HostedDomainHasBeenUnloaded;
AppDomain.Unload(host.GetAppDomain());
// wait for it to unload
aspNetHostIsUnloaded.WaitOne();
// optionally remove the bin directory
if (cleanBin)
{
Directory.Delete("bin", true);
}
aspNetHostIsUnloaded.Close();
}
}
}
This makes sense for testing ASPX pages, and that sort of thing. But I'm not so sure this is the right thing, for your scenario. There are more direct ways to generate text files. But, it may be right for you. If you really like the template engine idea, hosting ASPNET may be just the thing for you.
In your case, you would want to modify the custom Host so that the output for each page goes to a StringWriter instead of Console.Out, and then you could do Grep (or more likely a search with Regex) on that output. You might also want to modify it to accept all the input data as a querystring. You'd need to format the page request to do that.
EDIT: There's a good article on MSDN Magazine on this technique of hosting the ASPNET runtime. From December 2004.
EDIT2: There's a simpler way to manage the bin directory. Just create a symbolic link named bin, pointing to ".". Then, you can remove the symlink after the call to AppDomain.Unload(), without waiting. Looks like this:
public void Run(string[] pages)
{
bool cleanBin = false;
MyAspNetHost host = null;
try
{
// This creates a symlink.
// ASPNET always looks for a bin\ directory for the privateBinPath of the AppDomain.
// This will create the bin dir, pointing to the current dir.
if (!Directory.Exists("bin"))
{
cleanBin = true;
CreateSymbolicLink("bin", ".", 1);
}
host =
(MyAspNetHost) System.Web.Hosting.ApplicationHost.CreateApplicationHost
( typeof(MyAspNetHost),
"/foo", // virtual dir - can be anything
System.IO.Directory.GetCurrentDirectory() // physical dir
);
foreach (string page in pages)
host.ProcessRequest(page);
}
finally
{
// tell the host to unload
if (host!= null)
{
AppDomain.Unload(host.GetAppDomain());
if (cleanBin)
{
// remove symlink - can do without waiting for AppDomain unload
Directory.Delete("bin");
}
}
}
}
This eliminates the need for the ManualResetEvent, copying files, synchronization, etc. It assumes the assembly for the custom ASPNet Host as well as all the assemblies required by the ASPX pages you run are contained in the current working directory.
This sounds like a very similar issue which is generating HTML emails on a server. There are some answers here that do that (for MVC):
ASP.NET MVC: How to send an html email using a controller?
You can proceed in a similar fashion for non-MVC by loading and rendering a control (ASCX) to a file.

Categories

Resources