Read local/static file in Blazor Wasm - c#

My project is created in Blazor WASM ( I do not want to use Blazor server )
I would like to read XSD files from wwwroot:
Inside my XsdService.cs - c# class I was trying:
string pathToXsd = Path.Combine("plcda","extPL_r2.xsd");
string transformataHTML = System.IO.File.ReadAllText(pathToXsd);
However, I always get errors:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find a part of the path "/plcda/extPL_r2.xsd".
System.IO.DirectoryNotFoundException: Could not find a part of the path "/plcda/extPL_r2.xsd".
So is there any chance to include custom/static/local files to Blazor WASM? And read them even if app is offline?

Create a Http GET call to the files. Think of Blazor wasm as a SPA application. All of the files that are required to run your app are downloaded into a users browser. Everything else like images are fetched on request. Like an images is requested by the browser.
#inject HttpClient _client
#code {
async Task GetXDSFile()
{
var byteOfTheFile = await _client.GetByteArrayAsync("plcda/extPL_r2.xsd");
}
}
This sample just fetches the file as byte array. Other version of the Get maybe more sutaible for you like GetStreamAsync.

In .NET Core 6 you can add provider mappings to your client project's program.cs to serve static files.
For example I need to load a 3d model (.obj, .mtl files):
Blazor WASM Client Only Project:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");
builder.Services.Configure<StaticFileOptions>(options =>
{
options.ContentTypeProvider = provider;
});
await builder.Build().RunAsync();
If you have an asp.net core hosted project you can simply put this in the server project's program.cs file instead and you shouldn't need to add nuget package references.
Blazor WASM Asp.net Core Hosted Project:
using Microsoft.AspNetCore.StaticFiles;
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".babylon", "application/javascript");
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");
builder.Services.Configure<StaticFileOptions>(options =>
{
options.ContentTypeProvider = provider;
});
var app = builder.Build();

Related

How to add SPA Services for AngularJS project with .NET Core?

I'm rebuilding a project of mine from .NET Framework to .NET Core and was curious to see if I'm able to "plug" in my Angular JS front-end project into the new .NET Core project using SpaServices. I've found some tutorials and this is what I have (my Angular folder is in the same project as my Startup.cs and API):
In ConfigureServices() in Startup.cs:
services.AddSpaStaticFiles(config => {
config.RootPath = "/MyAngularProject";
});
In Configure() in Startup.cs:
app.UseSpa(spa => {
spa.Options.SourcePath = "/MyAngularProject";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
The Angular folder is not named 'ClientApp'. When I run my backend and then the Angular project in VS Code, I get this error:
AggregateException: One or more errors occurred. (One or more errors occurred. (Failed to start 'npm'. To resolve this:.
[1] Ensure that 'npm' is installed and can be found in one of the PATH directories.
There is also an Inner Exception:
[2] See the InnerException for further details of the cause.
---> System.ComponentModel.Win32Exception (267): The directory name is invalid.
I've looked and made sure my PATH variable is set to the node.js folder and the error is still being thrown. I don't think I'm pointing at the wrong directory either for my Angular project. I do have the package.json file that holds the start script in a folder within MyAngularProject. I've also tried navigating into that folder but it produces the same errors. Can anyone help point me in the right direction? Is this even possible given the project is AngularJS? Thank you for any help!
UPDATE:
Here is the folder structure:
Solution 'MyProject'
MyProject.API
Controllers (folder)
MyAngularProject (folder)
app (folder)
[npm script is located in here]
Startup.cs
Program.cs
appsettings.json

Does NltkNet the NLTK wrapper class support .NET core web applications or only console applications?

When I try to Initialize the NltkNet object in my dotnet core web application I receive an error saying an assembly is not found or has a different manifest definition than its assembly reference.
The code is fairly simple, it does nothing at all except initialize an NltkNet object when a button is clicked.
public IActionResult Upload()
{
Nltk.Init(new List<string>()
{
#"C:\IronPython27\Lib",
#"C:\IronPython27\Lib\site-packages",
});
return View();
}
I was able to get the exact same code to work in my console application without issue.
Is this a configuration issue on my end or is ASP.NET core MVC web application support not available for NltkNet?
I have discovered that NltkNet does not support dotnet core.

How to show swagger/ui/index page in .Net Framework 4.7 project which is deployed in IIS with .com

I have a web api project which is running in .NET Framework 4.7. I have added the Reference Swashbuckle.Core for showing the swagger ui. I have updated the .csproj also to add the documentation .xml file. It is working in my development machine when I run my application using the url http://localhost:55677/swagger/ui/index. But when i publish the application using visual studio, it is showing as "404 - File or directory not found". It might be because the UI page Swaggerui is not available in the published bin folder. The published url looks like "https://xxx.xxx.xxx.com". But after loading i give like "https://xxx.xxx.xxx.com/swagger/ui/index" to show the swagger ui. But it is showing the 404 error. I am not using any .net core project. Just .net framework only.
Someone please help me on this.
After looked into several sites, i have added these code part in the SwaggerConfig.cs file.
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "App Name");
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory + "bin\\", xmlFile);
c.IncludeXmlComments(xmlPath);
c.ApiKey(ConfigurationManager.AppSettings.Get("apikey"))
.Description("API Key Authentication")
.Name("key-name")
.In("header");
c.RootUrl(req =>
req.RequestUri.GetLeftPart(UriPartial.Authority) +
req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));
})
.EnableSwaggerUi(c =>
{
c.EnableApiKeySupport("key-name", "header");
});
RootUrl is the one i found from a site to redirect to SwaggerUI page. But it is not working.

asp.net core mvc view not found when starting via reflections

I am using an asp.net core mvc application based on .NET 4.7.
When I start generated sample Application, all works well.
But I have a bigger application with plugin support and I want to use asp.net mvc as one of my plugins.
The plugins are embedded loading the Assembly from the dll file and call a Start() method for starting the plugin.
When I add the asp.net start code in this Method, the web app starts by on any request I get this error:
Connection id "0HLJE77KODDC8", Request id "0HLJE77KODDC8:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
/Pages/Shared/Index.cshtml
bei Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)
bei Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.<ExecuteAsync>d__6.MoveNext()
But I know that the Index.cshtml exists.
I start asp.net app with
CreateWebHostBuilder(new string[] { }).UseContentRoot(myWebBinPath).Build().Run();
from the Method called via reflection.
All dll reference assembleis are resolved well but do I have to set an additional path when I call the CreateWebHostBuilder from an other application context (e.g. Environemt CurrentDirectory ...)
I don't know where the framework looks for this views, so I cant adjust the file path...
please help me :)
I got it:
ASP.NET want a valid AppDomain.CurrentDomain.BaseDirectory path to asp.net bin directory.
So I have to create a new AppDomain for speceific parts of my app.
In my test scenario it works when I force update AppBase Path:
AppDomain.CurrentDomain.SetData("APPBASE", #"D:\...\HomeDataManagement.Plugin.Service.Web\bin\Debug\net461\");
Then the app environment is the same as running the exe file standalone, so I can call WebBuilder without contentRoot path:
CreateWebHostBuilder(new string[] { }).Build().Run();

WebpackDevMiddleware in ASP.NET Core app in Azure Service Fabric

I am trying to use WebpackDevMiddleware with HotModuleReplacement in an ASP.NET Core app. I followed the following guide: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa-services in setting up webpack to work with ASP.NET.
When I deploy my ASP.NET Core app via Service Fabric, the following error is thrown:
Call to Node module failed with error: Webpack dev middleware failed
because of an error while loading 'aspnet-webpack'....
I noticed that inside my wwwroot/ folder, I have no node_modules, dependencies, etc... and so this error seems to make sense. The ASP.NET core app does not seem to have access to the aspnet-webpack node module. Additionally, in other projects' wwwroot folders there appears to be a dependencies folder visible in Visual Studio, while in mine there is no such folder.
I'm wondering how I can give the ASP.NET core app access to the modules it needs?
It seems that ServiceFabric does not support Hot Module Replacement at this time.
To get around this I added the following:
#if DEBUG
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
#endif
So that you only use HMR when in debug mode and when you publish to local/production cluster HMR is not used.

Categories

Resources