ASP.NET Client Validation Javascript Partially Rendering - asp.net-2.0

This is happening on my development machine and the same codebase is working in production. So I believe this to be an IIS/Framework issue. It affects all pages.
On both servers, the Page_Validators are setup correctly:
<script type="text/javascript">
<!--
var Page_Validators = new Array(document.getElementById("ValidatorInsurancePayerRequired"),
document.getElementById("ValidatorCheckPostDateRequired"),
document.getElementById("ValidatorCheckPostDateFormat"),
document.getElementById("ValidatorCheckNumberRequired"),
document.getElementById("ValidatorCheckTotalRequired"),
document.getElementById("ValidatorCheckTotalFormat"));
// -->
</script>
However, on my development machine it does not render the script block that sets the validation properties:
<script type="text/javascript">
<!--
var ValidatorInsurancePayerRequired = document.all ? document.all["ValidatorInsurancePayerRequired"] : document.getElementById("ValidatorInsurancePayerRequired");
ValidatorInsurancePayerRequired.controltovalidate = "txtPayer";
ValidatorInsurancePayerRequired.errormessage = "<br>Insurance Payer Is Required";
ValidatorInsurancePayerRequired.display = "Dynamic";
ValidatorInsurancePayerRequired.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
ValidatorInsurancePayerRequired.initialvalue = "";
.
. all other Page Validators
.
// -->
</script>
I have tried running aspnet_regiis -c to reinstall the validation scripts. Failing that I tried that with a -e (remove) followed by -i (install).
Any ideas?

What versions of .NET/IIS are you running? If this is a 2.0 implementation, try putting this in your web.config in the system.web section and see what happens:
<xhtmlConformance mode="Legacy"/>
Does this happen if you run using the ASP.Net Development Server?
Also, if tracing is enabled in development, try disabling it.
Short of these few suggestions, I'd really need a lot more info on your environments in order to assist further.

Related

Blazor: How to run my command before JS files compression / load blazor app from different domain

TL;DR: is there a Target during build/publish (in asp.net core Blazor app) for JS files compression which I can use in csproj to run my script before this Target?
Background:
I have Blazor frontend application which is loaded to different web application (different domains). So: main application loads many other applications and one of these applications is Blazor app (hosted at different URL).
What I did: I load manually _framework/blazor.webassembly.js with autostart property set to false and start Blazor manually:
Blazor.start({
loadBootResource: (
type: string,
name: string,
defaultUri: string,
integrity: string
) => {
const newUrl = ...;// here I can make some URL replacements for defaultUri
// so my `newUrl` points to place where Blazor app is hosted
return newUrl;
},
})
similar as described here: https://learn.microsoft.com/en-us/aspnet/core/blazor/host-and-deploy/webassembly?view=aspnetcore-3.1#custom-boot-resource-loading
It works correctly but one file is NOT loaded through loadBootResource. It is blazor.boot.json. Code which loads this file is located in blazor.webassembly.js (fetch("_framework/blazor.boot.json"...): https://github.com/dotnet/aspnetcore/blob/master/src/Components/Web.JS/src/Platform/BootConfig.ts#L6
Problem is described also in this issue https://github.com/dotnet/aspnetcore/issues/22220
There is also possible solutions suggested by me: https://github.com/dotnet/aspnetcore/issues/22220#issuecomment-683783971
I decided to replace content of blazor.webassembly.js (replace fetch("_framework/blazor.boot.json" with fetch(${someGlobalVariableForSpecificDomainURL}/_framework/blazor.boot.json) but there are also compressed files (GZ and BR). How to run my script for replacement before compression is started but after JS file is generated? Is it possible? Is there any Target which I can use in csproj?
I do not want to disable dotnet files compression and I do not want to overwrite compressed files (compress by my own).
My current csproj contains something like this (script is started after compression so too late):
<Target Name="ReplacementDuringBuild" BeforeTargets="Build">
<Exec WorkingDirectory="$(MyDirWithScripts)" Command="node replace.js --output=$(MSBuildThisFileDirectory)$(OutDir)" />
</Target>
<Target Name="ReplacementDuringPublish" AfterTargets="AfterPublish">
<Exec WorkingDirectory="$(MyDirWithScripts)" Command="node replace.js --output=$(MSBuildThisFileDirectory)$(PublishDir)" />
</Target>
Thanks for a help or any suggestion! If there is also another workaround to solve main issue, then I will be glad to see it (base tag does not work; replacement of fetch also is not so good).
I didn't find any fitting Target for my purpose. Code from question worked correctly but only with my own compression. So I reverted this and finished with overriding window.fetch to resolve main issue. If URL contains blazor.boot.json then I modify URL and pass it to original fetch. After all files are loaded, I restore original fetch. Similar to code suggested here: https://github.com/dotnet/aspnetcore/discussions/25447
const originalFetch = window.fetch;
window.fetch = function(requestInfo, options) {
if (requestInfo === '_framework/blazor.boot.json') {
return originalFetch('https://example.com/myCustomUrl/blazor.boot.json', options);
} else {
// Use default logic
return originalFetch.apply(this, arguments);
}
};

WSO2 API Manager is saving hundreds of 'publisher' HTML files to directory

WSO2 API Manager is saving hundreds of 'publisher' HTML files (every day) to directory "/root"
All of the files have names like:
publisher.1
publisher.2
publisher.3
...
publisher.978
etc
How do I stop it from creating these files, or atleast how can I change the output directory for the files?
The contents of each file is HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var requestURL = '/publisher';
var ssoEnabled = 'false';
var tenantDomain = 'null';
</script>
<title>API Publisher- Login</title>
<meta charset="UTF-8">
...
...
...
<script>
var siteRoot = '/publisher/site/themes/wso2';
</script>
<script type="text/javascript" src="/publisher/site/themes/wso2/libs/jquery.cookie.js"></script>
<script type="text/javascript" src="/publisher/site/themes/wso2/templates/utils/button-loader/jquery.buttonLoader.js"></script>
</body>
</html>
Looked in a bunch of config files, and in carbon management settings, but can't find anything that looks like it controls this.
Expect no html files to be saved at all to root directory.
By going through the file content you have given, It seems, it's a rendered output of a publisher page.
Because the following script tag is coming from the base template in WSO2 API Manager publisher app.
<script>
var requestURL = '/publisher';
var ssoEnabled = 'false';
var tenantDomain = 'null';
</script>
But there is no possibility to write the rendered HTML pages to /root/ directory or to anywhere else in the file system.
And also by default (In Unix systems), only root user has Read, Write permission to the /root/ directory. So unless you run a tool with root permission, It can't write files to the /root/ directory.
WSO2 API Manager does not need root permission to run nor it's recommended to start the server with superuser privileges.
So I think, this should have done by some external tool.
For example: If you have configured a health-check tool to GET a /publisher page and write the snapshot of the page to file system each time you perform the health check and if that is configured to write to /root/ directory this could have happened.
Can you check
Whether these files are created in equal time intervals
Who is the owner of these files (ls -lh)
And also check whether WSO2 API Manager is running with the same user who has created those files (ps -aux | grep wso2server).

Laravel generates an error "Echo is Echo is not defined"

I am working with Laravel Event Broadcasting and i am using pusher driver for broadcasting event and its working perfectly.
The public channel is subscribed successfully from client side using pusher provided js library
var pusher = new Pusher('xxxxxxxxxxxxxxxxxxxxx_my_app_key', {
encrypted: true
});
var channel = pusher.subscribe('TestPusher');
channel.bind('App\\Events\\TestPusher', function(data) {
alert(data.msg);
});
But when i use Echo in my client side code
Echo.channel('TestPusher')
.listen('TestPusher', (e) => {
console.log(e.msg, e.chatMessage);
});
It generates the error " Echo is not defined ".
I already installed the Laravel Echo library using npm install --save laravel-echo pusher-js in my application and also included the following code in resources/assets/js/bootstrap.js file as per the laravel provide documentation.
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'xxxxxxxxxxxxxxxxxxxxx_my_app_key'
});
So please help me how can i fix this problem.
My issue was that I was not compiling bootstrap.js together with the rest of the code because I had removed the line require('./bootstrap') from app.js. I added that line back and I was home and dry.
As described here
I had this problem a few days ago. My gulp installation was all messed up and Laravel versioning didn't help.
Sorry if this doesn't help, it's just my experience and most detailed as possible:
First, I'll consider you do have the js/app.js script included on you site.
Now, you're seeing this error because, as Josh mentioned, you're not compiling your js files. After editing 'resources/assets/js/bootstrap.js', this file needs to be compiled by running the asset compiler: gulp (named Laravel Elixir docs/5.3/elixir) in Laravel 5.3).
If you followed carefully this part of the tutorials, you shall be extra careful with laravel's npm dependencies versions, specially those used by Elixir (Once again, my gulp installation wasn't working at all even though no error messages showed up).
So, if this is a new project, you should consider updating to Laravel 5.4. If you can't or not willing to update all Laravel framework, perhaps this can be solved like I did. Staying at 5.3 but using the latest assets compiler on 5.4, named Laravel Mix. Now it runs on npm: npm run dev. (No gulp mentioned on doc.)
To achieve this, you should update to latest package.json on 5.4 and follow the 5.4 documentation to install Laravel Mix.
Your codes looks fine, Problem is your JS order so only you getting undefined issues
like
<script>
Echo.channel('TestPusher')
.listen('TestPusher', (e) => {
console.log(e.msg, e.chatMessage);
});
</script>
<script src="echo.js"></script>
so zigzag the order :)
widow object before each Echo.
window.Echo.channel('TestPusher')
.listen('TestPusher', (e) => {
console.log(e.msg, e.chatMessage);
});
remove defer from your app.js script tag
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>

Do I need to have a Startup.cs on my Frontend?

This question is related to this:
The problem I'm having is that I am trying to implement a SignalR with CORS from one ASP.NET (localhost:50000) project called Frontend to another ASP.NET MVC project (in the same solution) (localhost:60000).
When I run the application I get this error message in the console:
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class. To disable OWIN startup discovery, add the appSetting
owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the
appSetting owin:AppStartup with the fully qualified startup class or
configuration method name in your web.config.
When I add a OWIN Startup class I don't get this error message:
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
And I guess it's because it is trying to find the hubs in it's own project.
Question 1:
Do I need a startup on my Frontend?
Question 2 (if Question 1 == yes):
Must I in the Startup map SignalR to my Backend?
EDIT:
index.html:
<!--Script references -->
<link href="Content/bootstrap.min.css" rel="stylesheet">
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:50000/signalr/hubs" type="text/javascript"></script>
<!-- HEAD ^^^ -->
<!-- Deleted stuff -->
<!-- BODY vvv -->
<script type="text/javascript">
$(function () {
var broadcaster = $.connection.loginHub;
console.log("broadcaster: " + broadcaster)
$.connection.hub.start().done(function () {
});
});
</script>
After re-creating my Frontend project and only installing the Microsoft.AspNet.SignalR.JS package I know receive this error in the console:
HTTP Error 404.0 - Not Found .... Requested URL
http://localhost:60000/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1443076975867
http://localhost:60000 is the Frontend so I'm not sure why that is the requested URL.
When checking http://localhost:50000/signalr/hubs I get a website from ASP.NET SignalR JavaScript Library v2.2.0 and also when I print out broadcaster in the console it says broadcaster: [object Object] so some sort of connection seems to be established.
You probably need to set up the client to point to your actual hub location since by default it's the current server.
$.connection.hub.url = '<yourbackendurl>;
Do that before connection.hub.start is called and it should work for you.
In your Backend project you need to install these packages:
PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Microsoft.Owin.Cors
And its Startup class should be like this:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
In your Frontend project you need to install this package:
PM> Install-Package Microsoft.AspNet.SignalR.JS
Also you can install SignalR for .NET client:
PM> Install-Package Microsoft.AspNet.SignalR.Client

How to Ensure Latest Javascript & CSS in Browser Cache in ASP.NET MVC

I would like to ensure that latest version of js & css are in client browser cache. I have followed this link (http://blog.robvolk.com/2009/04/ensure-latest-javascript-css-in-browser.html?showComment=1354714427404#c5850523542624593865)
The problem I am not getting new hash-code on every build. I even try to clean and rebuild it does have the same hash-code.
I would appreciate if someone could advise how can I handle the browser cache.
Thanks
I would suggest using bundling and minification of scripts and stylesheets. It is a new feature introduced together with MVC 4, but it seems, that someone was able to make it work with even MVC3 - ASP.NET MVC4 bundling in ASP.NET MVC3
ASP.NET Optimization uses similar approach as your solution - it appends a hash to the URL of script/style, but this hash is based on the content of the js/css file, not on an instance of the application assembly.
note: the blogpost by Jef Claes uses Microsoft.Web.Optimization package, that was replaced by Microsoft.AspNet.Web.Optimization, but I believe, it will work even with the Microsoft.AspNet.Web.Optimization package.
UPDATE: The previous version did not work on Azure, I have simplified and corrected below. (Note, for this to work in development mode with IIS Express, you will need to install URL Rewrite 2.0 from Microsoft http://www.iis.net/downloads/microsoft/url-rewrite - it uses the WebPi installer, make sure to close Visual Studio first)
I fought with it for a couple of days and ended up rolling my own. (see link below for full explanation) You basically Auto-increment the assembly version every time the project is built, and use that number for a routed static file on the specific resources you would like to keep refreshed. (so something.js is included as something.v1234.js with 1234 automatically changing every time the project is built) - I also added some additional functionality to ensure that .min.js files are used in production and regular.js files are used when debugging (I am using WebGrease to automate the minify process) One nice thing about this solution is that it works in local / dev mode as well as production. (I am using Visual Studio 2015 / Net 4.6, but I believe this will work in earlier versions as well.
To implement, you can follow the following steps: (I know this is an old post, but I ran across it while developing a solution):
How to do it: Auto-increment the assembly version every time the project is built, and use that number for a routed static file on the specific resources you would like to keep refreshed. (so something.js is included as something.v1234.js with 1234 automatically changing every time the project is built) - I also added some additional functionality to ensure that .min.js files are used in production and regular.js files are used when debugging (I am using WebGrease to automate the minify process) One nice thing about this solution is that it works in local / dev mode as well as production. (I am using Visual Studio 2015 / Net 4.6, but I believe this will work in earlier versions as well.
Step 1: Enable auto-increment on the assembly when built
In the AssemblyInfo.cs file (found under the "properties" section of your project change the following lines:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
to
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
Step 2: Set up url rewrite in web.config for files with embedded version slugs (see step 3)
In web.config (the main one for the project) add the following rules in the <system.webServer> section I put it directly after the </httpProtocol> end tag.
<rewrite>
<rules>
<rule name="static-autoversion">
<match url="^(.*)([.]v[0-9]+)([.](js|css))$" />
<action type="Rewrite" url="{R:1}{R:3}" />
</rule>
<rule name="static-autoversion-min">
<match url="^(.*)([.]v[0-9]+)([.]min[.](js|css))$" />
<action type="Rewrite" url="{R:1}{R:3}" />
</rule>
</rules>
</rewrite>
Step 3: Setup Application Variables to read your current assembly version and create version slugs in your js and css files.
in Global.asax.cs (found in the root of the project) add the following code to protected void Application_Start() (after the Register lines)
// setup application variables to write versions in razor (including .min extension when not debugging)
string addMin = ".min";
if (System.Diagnostics.Debugger.IsAttached) { addMin = ""; } // don't use minified files when executing locally
Application["JSVer"] = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace('.','0') + addMin + ".js";
Application["CSSVer"] = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace('.', '0') + addMin + ".css";
Step 4: Change src links in Razor views using the application variables we set up in Global.asax.cs
#HttpContext.Current.Application["CSSVer"]
#HttpContext.Current.Application["JSVer"]
For example, in my _Layout.cshtml, in my head section, I have the following block of code for stylesheets:
<!-- Load all stylesheets -->
<link rel='stylesheet' href='https://fontastic.s3.amazonaws.com/8NNKTYdfdJLQS3D4kHqhLT/icons.css' />
<link rel='stylesheet' href='/Content/css/main-small.#HttpContext.Current.Application["CSSVer"]' />
<link rel='stylesheet' media='(min-width: 700px)' href='/Content/css/medium.#HttpContext.Current.Application["CSSVer"]' />
<link rel='stylesheet' media='(min-width: 700px)' href='/Content/css/large.#HttpContext.Current.Application["CSSVer"]' />
#RenderSection("PageCSS", required: false)
A couple things to notice here: 1) there is no extension on the file. 2) there is no .min either. Both of these are handled by the code in Global.asax.cs
Likewise, (also in _Layout.cs) in my javascript section: I have the following code:
<script src="~/Scripts/all3bnd100.min.js" type="text/javascript"></script>
<script src="~/Scripts/ui.#HttpContext.Current.Application["JSVer"]" type="text/javascript"></script>
#RenderSection("scripts", required: false)
The first file is a bundle of all my 3rd party libraries I've created manually with WebGrease. If I add or change any of the files in the bundle (which is rare) then I manually rename the file to all3bnd101.min.js, all3bnd102.min.js, etc... This file does not match the rewrite handler, so will remain cached on the client browser until you manually re-bundle / change the name.
The second file is ui.js (which will be written as ui.v12345123.js or ui.v12345123.min.js depending on if you are running in debug mode or not) This will be handled / rewritten. (you can set a breakpoint in Application_OnBeginRequest of Global.asax.cs to watch it work)
Full discussion on this at: Simplified Auto-Versioning of Javascript / CSS in ASP.NET MVC 5 to stop caching issues (works in Azure and Locally) With or Without URL Rewrite (including a way do it WITHOUT URL Rewrite)

Resources