Html Widget src appears and then disappears on refresh - html

My HTML Script tag has a src, but then the div id to display the widget appears and then disappears on refresh. The DIV is still there but its not bringing in the source.
I don't know why as I get no error message in the Javascript debugger.
One weird thing is it doesn't disappear in Localhost but ONLY in Azure.
Refresh the page to re-produce the issue.
I'm using Blazor .NET Core, and the widget is at:
Site:
https://markstest1.azurewebsites.net/
Source file:
https://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute
Source Code
Startup.cs (CORS added for site). One site is http.
Could that be an issue?
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(//name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://www.climatelevels.org", "http://www.2degreesinstitute.org")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
DIV Tag with id to source file. Razor file.
<div id="co2-widget-container"></div>
_Host.cshtml file with tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="https://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute"></script></script>

Seems to be loading now correctly. The answer was that Blazor was starting too early and canceling the javascript loads in the _Host file. It seems I had to add the tag
<script src="_framework/blazor.server.js" autostart="false"></script>
to the Blazor script file so it doesn't start too quickly and let's the startup file initiate Blazor instead. Then mutate the src URL into a Blazor.start() call after DOMContentLoaded is loaded.
<script>document.addEventListener("DOMContentLoaded", function () {
Blazor.start().then(function () {
var customScript = document.createElement('script');
customScript.setAttribute('src', '//www.website...');
document.head.appendChild(customScript);
});
});</script>
Resource link used:
https://github.com/dotnet/aspnetcore/issues/22643
https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-5.0

Related

Is it possible to use aspx.cs file as a server end controller?

I am fairly new to web forms. I am using custom file upload component. I would like to upload file in a specific folder of my local machine and I have written code in the Default.aspx.cs file instead of Default.ahsx page. The file which I upload is uploaded successfully(UI level only) and I'm getting wondered, I cannot able to get the file in code behind (i.e., in aspx.cs file). Breakpoints also not hit. In the Network tab of browser, status code is returned as 200.
Here is what I've tried.
My aspx.cs file
public static object Save(HttpContext context)
{
// Debugger is not hitting
<Code to save file>
return "";
}
Aspx file
<div id="app">
<custom-uploader :async-settings="path"></custom-uploader>
</div>
<script>
Vue.use(customUploader.UploaderPlugin);
new Vue({
el: '#app',
data: function () {
return {
path: {
saveUrl: 'Default.aspx/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
}
}
});
</script>
Any help would be greatly appreciated.

polymer serve vs. static web server

What kind of magic is polymer-serve doing that I don't get with a simple, static web server?
I just started with a simple "hello world" project. When I run polymer serve I'm able to browse to the page at http://localhost:8000/example.html and it works great. If I use static-server and browse to the same page, I get an error message in Chrome.
Uncaught TypeError: Failed to resolve module specifier "#polymer/lit-element". Relative references must start with either "/", "./", or "../".
Here's example.html, which was copied right out of the README.
<script src="node_modules/#webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
<script type="module">
import { LitElement, html } from "#polymer/lit-element";
class MyElement extends LitElement {
static get properties() {
return {
mood: { type: String }
};
}
constructor() {
super();
this.mood = "happy";
}
render() {
return html`
<style>
.mood {
color: green;
}
</style>
Web Components are <span class="mood">${this.mood}</span>!
`;
}
}
customElements.define("my-element", MyElement);
</script>
<my-element mood="happy"></my-element>
Modules are imported by name instead of by path
check for instance this reference
From it
This change brings Polymer in line with standard npm practice, and
makes it easier to integrate Polymer with other tools and projects.
However, because browsers don't yet support importing modules by name,
it means you'll need a transform step to run Polymer modules natively
in the browser. The Polymer CLI and related tools are being updated to
do this transformation automatically.
running polymer build should create converted files (referenced by path)

Razor engine cant find view

I'm trying to render a HTML from a view without using a web request. I need the HTML as a string, internally, I do not wish to serve it.
The viewEngine.FindView() returns a viewEnineResult that shows no view was found. It shows to search locations where it looked they look like this:
/Views//PDFOperationsReportView.cshtml
/Views/Shared/PDFOperationsReportView.cshtml
(Observe the double forward slash in the first line)
File structure (I placed it into a HTML snippet cause I couldn't manage to format the text properly in this editor)
Project
Folder
Subfolder
CodeFile.cs
Views
PDFOperationsReportView.cshtml
The code:
var viewName = "PDFOperationsReportView";
var actionContext = GetActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
}
var view = viewEngineResult.View;
I had the same issue. I found the answer here: GitHub aspnet/Mvc Issue #4936
Basically, use GetView instead of FindView, like this:
var viewResult = razorViewEngine.GetView(viewName, viewName, false);
Your viewName needs to be a full path for this to work. For example:
/Views/Shared/PDFOperationsReportView.cshtml
~/Pages/Shared/_Article.cshtml
~/Areas/CM/Pages/_Article.cshtml
We have a helper method defined to render optional views which may or may not exist:
public static Task RenderPartialAsyncIfExists(this IHtmlHelper htmlHelper, ICompositeViewEngine engine, string partialViewName, object model)
{
if (engine.GetView(partialViewName, partialViewName, false).Success)
{
return htmlHelper.RenderPartialAsync(partialViewName, model);
}
return Task.CompletedTask;
}
It's used on view pages like:
#inject ICompositeViewEngine Engine
...
#{ await Html.RenderPartialAsyncIfExists(Engine, $"~/Views/Shared/_navigationAdmin.cshtml"); }
This works find locally (IIS Express) but for some reason was failing when deployed to IIS.
In my case, there was something wrong with the .csproj file, where the view in question was removed but then re-added as an embedded resource:
<ItemGroup>
<Content Remove="Views\Shared\_navigationAdmin.cshtml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Views\Shared\_navigationAdmin.cshtml" />
</ItemGroup>
Removing those two sections from the .csproj fixed the problem in IIS.
This is using (EOL) AspNet Core 2.2

How do I allow an MIME extension map in ASP.NET vNext?

Background
I have a piece of LESS code that needs to be compiled at runtime with Less.js -- it calculates some things via JavaScript -- so I can't use the task runner, etc.
In my index.html, I have:
<head>
...
<link rel="stylesheet/less" href="assets/less/DynamicHeight.less" />
...
<script type="text/javascript" src="lib/less/less.js"></script>
...
</head>
Problem
Less.js appears unable to find the file:
And when I try to access the file directly, I see:
Question
How can I add the configuration that will allow this less file to be downloaded? Am I still able to use web.config files with vNext, or do I need to do something with config.json instead?
Lead 1: Should I use Owin?
Thinking this might be the right path but I'm pretty unfamiliar.
I see a number of tutorials out there, such as K. Scott Allen's, which reference code such as:
public void Configuration(IAppBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
However, it appears that in its current version, asp.net is looking for a signature of Configure(IApplicationBuilder app) instead.
The IApplicationBuilder class doesn't have a method along the lines of UseStaticFiles -- it only has a signature of IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware).
I have a feeling that this is likely the right path to solve the issue -- I just can't find out how to propertly configure the IAppliationBuilder to map the MIME extension.
Okay, I believe I figured it out.
Step 1: Add the appropriate library for static files
In ASP.NET vNext, this is Microsoft.Aspnet.StaticFiles.
In your project.json file, add the following under "dependencies":
"Microsoft.AspNet.StaticFiles": "1.0.0-beta2"
This adds the static middleware method that you can use later.
Step 2: Configure the app to use Static Files
Add the using statement at the top:
using Microsoft.AspNet.StaticFiles;
At this point, the app.UseStaticFiles method will be available, so your Configure method can look as follows:
public void Configure(IApplicationBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
And voila! I get text when browsing to .less files, and no more error is appearing from LessJS.
In .NET Core 1.0.1, SeanKileen answer is still good. The following is a simple code rewrite:
public void Configure(IApplicationBuilder app, ...)
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings[".map"] = "application/javascript";
contentTypeProvider.Mappings[".less"] = "text/css";
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = contentTypeProvider
});
The above code EXTENDS the default mapping list (see the source), which already has ~370 mappings.
Avoid using the FileExtensionContentTypeProvider constructor overload that takes a dictionary (as suggested by JHo) if you want those 370 default mappings.
SeanKilleen's answer is right on, and still works ASP.NET Core RC1. My only improvement is to write the exact same code using collection initializers to make it cleaner.
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".less", "text/css" },
{ ".babylon", "text/json" },
// ....
})
});

refresh data read from text file with out page refresh

i am a novice at Java and JS so this will be very basic.
I've got this code that creates a text file in a specific directory. i only got as far as creating an actuale file, however, as the text file will be frequantely updated, i need the page to refresh/reload the text file and display it's data (just in the blank page). How do i do this, with out user needed to click refresh (auto refresh in sense, however, i've tried auto refresh and it does not seem to reload JS and/or display text file's content)
Create Text file/Read/Display content/Refresh and/or Reload - no user refresh
<script>
function createFile()
{
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.CreateTextFile("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", false);
file.WriteLine('Hello World');
file.WriteLine('Hope is a thing with feathers, that perches on the soul.');
file.Close();
}
</script>
this will not accomplished by using client side javascript only you have to use server side code:
server ex (using node.js):
server :
var http = require("http"),
fs=require("fs");
http.createServer(function(request, response) {
fs.writeFileSync("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", 'Hello World\r\nHope is a thing with feathers, that perches on the soul.');
}).listen(8888);
client
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
$.get("http://localhost:8888",function(){
console.log("writing to file successeded");
})
})
</script>