Web optimizer .net core - jquery-ui

Upgrading .net 4.8 mvc app to .net 6. I am keeping the static content in the same folders as in the previous web app project and using the web optimizer to minify and bundle.
I am seeing lot of console errors and the UI is not loading for the app
Layout cshtml
Script and Content folder

It may help if you could show how you configured in program.cs
I tried as the document :
In program.cs:
builder.Services.AddWebOptimizer(x =>x.AddJavaScriptBundle("/js/bundle.js", "js/chat/*.js"));
call
app.UseWebOptimizer();
before:
app.UseStaticFiles();
in chat.js:
console.log("chat");
in hellow.js:
console.log("hellow");
And my project:
in my View,I called:
<script src="/js/bundle.js"></script>
The result:
other document may help:
Update:
I tried to add two floders under the directory of the project as your comment and tried as below to fix the 404 error:
var provider1 = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Script1"));
var provider2 = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Script2"));
builder.Services.AddWebOptimizer
(x =>
{    
x.AddJavaScriptBundle("/bundle1.js","/chat/*.js").UseFileProvider(provider1);
   x.AddJavaScriptBundle("/bundle2.js","/comment/*.js").UseFileProvider(provider2);
});
My project:

Related

Calling Another Project's Controller From A Project In The Same Solution (.NET Core )

There are 2 projects in the same solution. First project is a .NET Core project and it has all the codes(controllers, models etc.) related to packages. I need to get the information (id, name, description) of the packages and display it in the second project(.NET Core Web App with Razor). Is it possible to do it without changing the first project? I only want to show the package list on a single web page.
I tried calling the first project's controller but it didn't work. Maybe I missed a point. Any help is appreciated.
This requirement can be achieved, please see the gif image below.
Tips
If you want to call another project's controller from a project in the same solution, you need to make sure there is in HomeController in both project. I mean the name of any class should be unique in both projects.
Otherwise you will face the same issue like my homepage.
Test Code:
public List<PackageReference> GetPackageList5(string projectname)
{
List<PackageReference> list = new List<PackageReference>();
PackageReference p = null;
XDocument doc = XDocument.Load(_webHostEnvironment.ContentRootPath+ "/"+ projectname + ".csproj");
var packageReferences = doc.XPathSelectElements("//PackageReference")
.Select(pr => new PackageReference
{
Include = pr.Attribute("Include").Value,
Version = pr.Attribute("Version").Value
});
Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
foreach (var packageReference in packageReferences)
{
p = new PackageReference();
p.Version= packageReference.Version;
p.Include= packageReference.Include;
list.Add(packageReference);
//Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
}
return list;
}
My Test Steps:
create two project, Net5MVC,Net6MVC
add project reference.
My .net6 project references a .net5 project. So in my HomeController (.net), I add below:
using Net5MVC.ForCore6;
using Net5MVC.Models;
Suggestion
When we reference the .net5 project in .net6 project, we can build success, but when we deploy it, it always failed. The reason is some file was multiple publish output files with the same relative path.
Found multiple publish output files with the same relative path:
D:\..\Net6\Net6\Net5MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net6MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net5MVC\appsettings.json,
D:\..\Net6\Net6\Net6MVC\appsettings.json.
And usually will add class library to current project, not add a web project.
As we know we can find packages info in .csproj file, so we need copy and paste .csproj file to publish folder.
I still recommend using the GetPackageList5 method above as an interface for your project, using HttpClient for requests.

wwwroot serving pages not MVC6

I am currently working on an Asp.Net 5 / mvc 6 app. I was running the beta5 release and updated to beta7. I have noticed my index page is loading from the wwwroot directory (I started the app with an index page in the wwwroot and am now using mvc, making the index in the wwwroot redundant)
All of my mvc views were loading correctly prior to the update to beta7, I ideally do not want to go back to beta5.
I have included mvc in the Startup.cs
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",//optional id
defaults: new { controller = "App", action = "Index" }
);
});
Project.json
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta7",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta7",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
"Microsoft.Framework.Configuration.FileExtensions": "1.0.0-beta8",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
},
So after upgrading to beta8 and running dnvm upgrade this has resolved my issue. I believe my configuration was not entirely in line. Thanks to meligy & juergen-gutsch for their answers, very useful to know.
In your Startup class ("Startup.cs" file under src/project-name), in the Configure() method, this line:
app.UseStaticFiles();
probably comes before:
app.UseMvc(routes => ... );
You can change the order so that UseMvc(...) comes before UseStaticFiles(...), but note that this means MVC will try to handle all requests to images etc as well even if it doesn't need to.
You can also just change-the-name-of / move / remove the index file now that don't need it anyway.
Create a complete new ASP.NET 5 project and compare the project.json and the startup.cs with that files from your updated project.
This is the best option to see what is wrong with your current configuration.

Unable to minify css in asp.net mvc

I am trying to minify a css file using System.Web.Optimizations and it won't work
var fontAwsomeBundle = new Bundle("~/bundles/css/font-awsome", new CssMinify())
.Include("~/content/packages/font-awesome/css/font-awesome-{version}.css", new CssRewriteUrlTransform());
I have run site with optimizations enabled and debug=false
There is no pre-minified file in the same location
.net 4.5, IIS Express
System.Web.Optimizations 1.1.0.0, WebGrease 1.6.5135.21930. I tried updating WebGrease to latest, but that didn't work
I am not getting any minification errors in the bundle file, just unminified version of file
Tried this version as well. fontAwsomeBundle.Transforms.Add(new CssMinify());
You should use the StyleBundle for .css and ScriptBundle for .js.
var fontAwsomeBundle = new StyleBundle("~/bundles/css/font-awsome", new CssMinify())
.Include("~/content/packages/font-awesome/css/font-awesome-{version}.css", new CssRewriteUrlTransform());

Custom script transform in ASP.NET MVC bundle ignored when debug is false and minified file exists

I'm working on an MVC 5.0 (.Net 4.5) application where I need to apply a custom JavaScript transform to my included bundle files. One of those files, which I'm calling dummy.js for illustration purposes, has a minified file called dummy.min.js.
I created a custom script transform to replace injected window.jQuery references with a different expression. Everything works fine when I run locally and in debug mode, but when debug mode is turned off in the Web.config file, the Bundle returns the contents of the dummy.min.js file, but my script transform is not applied to it. It only gets applied to JavaScript files that don't have an associated .min.js file.
Does anyone have an idea on how to resolve this? It almost sounds like a bug in MVC.
A workaround is to remove the minified file. This post kind of addresses my situation by suggesting removing the .min.js file since MVC minifies by default, but I'm looking for an alternative solution (if any).
Thank you so much in advance.
Here's how to reproduce the above:
If you're interested in reproducing my issue, here's a quick BundleConfig and the actual custom script transform. It replaces all instances of window.jQuery with window.$jq1_9||window.jQuery, assuming it is injected via a self-executing anonymous function.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(
new ScriptBundle("~/bundles/dummy")
.Include("~/Scripts/dummy.js", new InjectedJQueryVariableRewriteTransform()));
}
}
public class InjectedJQueryVariableRewriteTransform : System.Web.Optimization.IItemTransform
{
public string Process(string includedVirtualPath, string javaScriptCode)
{
// TODO: I understand this approach is naiive, but it does the trick for now.
return javaScriptCode.Replace("window.jQuery", "window.$jq1_9 || window.jQuery");
}
}
If you have Visual Studio 2012 and MVC 4, you will need version 1.1.0 of the System.Web.Optimization assembly, which you can obtain by running the following command in the Nuget Package Manager. At time of writing it installs version 1.1.2 of the package.
Install-Package Microsoft.AspNet.Web.Optimization
Here's the sample JavaScript dummy.js. You can create a copy of it and name it dummy.min.js:
(function ($) {
"use strict";
// TODO: Do something interesting...
})(window.jQuery);
Set the debug attribute to false in the following element in Web.config:
<compilation debug="false" targetFramework="4.5" />
Assuming the application's port is 9221, render the bundle in Firefox or Chrome:
http://localhost:9221/bundles/dummy
You will see that when debug is set to true, the transform is applied, as shown below:
(function(){"use strict"})(window.$jq1_9||window.jQuery)
When it is set to false. It is ignored and only the .min.js file is used:
(function(){"use strict"})(window.jQuery)
If you add this line:
bundles.FileExtensionReplacementList.Clear();
you will remove the rule for using .min files when bundling is enabled. You will remove all rules, unfortunately, so if you need any of the other ones you'll need to add them manually. Also, this will change the rules for all bundles.
If you just want to disable these replacement rules for just one bundle, you can just set the EnableFileExtensionReplacements property to false on that specific bundle:
var bundle = new ScriptBundle("...");
bundle.EnableFileExtensionReplacements = false;

ASP.NET 4.5 Bundling in Debug Mode - Stale Resources

Is there any way we can make the ASP.NET 4.5 Bundling functionality generate GUID's as part of the querystring when running in debug mode (e.g bundling turned OFF).
The problem is when developing locally, the scripts/CSS files are generated like this:
<script type="text/javascript" src="/Content/Scripts/myscript.js" />
So if i change that file, i need to do a hard-refresh (sometimes a few times) to get the file to be picked up by the browser - annoying.
Is there any way we can make it render out like this:
<script type="text/javascript" src="/Content/Scripts/myscript.js?v=x" />
Where x is a GUID (e.g always unique).
Ideas?
I'm on ASP.NET MVC 4.
Until the NuGet package is patched as per the other answer above, for now i've ended up using the same wrapper code i did for the beta NuGet package:
private static IHtmlString JsUnbundled(this HtmlHelper htmlHelper, string bundlePath)
{
var jsBuilder = new StringBuilder();
foreach (var file in BundleResolver.Current.GetBundleContents(bundlePath))
{
var tagBuilder = new TagBuilder("script");
tagBuilder.Attributes["src"] = file.AddCacheKey(); // add GUID
tagBuilder.Attributes["type"] = "text/javascript";
jsBuilder.AppendLine(tagBuilder.ToString());
}
return MvcHtmlString.Create(jsBuilder.ToString());
}
I then have another HTML helper which checks if debug, then uses the above - otherwises uses Scripts.Render.
Obviously this doesn't do any kind of hashing of the file - it will ALWAYS request the file. But i don't mind this, as it's only for debug.
We don't currently examine the contents of the files in debug mode, but we could add this feature.
I filed it as an issue on codeplex here.
Try HashCache: https://github.com/kemmis/System.Web.Optimization.HashCache
Execute the ApplyHashCache() extension method on the BundlesCollection Instance after all bundles have been added to the collection.
BundleTable.Bundles.ApplyHashCache();
This will add content hashes to the script/style tags output when in debug mode.

Resources