.NET 6 Blazor WASM. Can't Find appsetting.json File - blazor-webassembly

In my program.cs I have
var config = builder.Configuration;
try
{
config.AddJsonFile("appsettings.json");
}
catch (Exception ex)
{
}
I am getting the exception
'The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was '/appsettings.json'.'
The file appsettings.json is in the root directory of the project and copy to output directory is "Copy always".
I also tried using:
try
{
IConfigurationBuilder config2 = new ConfigurationBuilder().AddJsonFile("appsetting.json");
config2.Build();
}
catch (Exception ex)
{
}
This has the same error. Why is the file not found?

Seems the appsettings.json goes into WWWROOT FOLDER in a Blazor WASM peoject not project root.

Related

How can i get logs/debugging for an error 500?

I'm working on a .NET Core 2.0 web application. I got a mocked database where application works good. Today i created a clean database and got this error 500 both on IIS Express and on regular IIS.
The thing is: i couldn't debug why is throwing the error 500. The application just run.
I've currently tried:
Check IIS logs by activating stdoutLogEnabled="true" and the only log created was:
Hosting environment: Production Content root path:
C:\Users\pistolon\Downloads\peto Now listening on:
http://localhost:13361 Application started. Press Ctrl+C to shut down.
Debugging from start the startup.cs file.
When I switch back to the mocked db it works without error.
Do you any of you could point me on where could i get an exception or log for this?
You can use Event Viewer or Visual Studio Remote Debugging to debug your deployed applications.
Also, you can use a logging framework like Serilog and use one of it sinks like file sink and create a middleware which catches and logs your exceptions and write their StackTrace, Message, Source to a log file that you can read them.
Here is ErrorHandlingMiddleware implementation :
public class ErrorHandlingMiddleware
{
readonly RequestDelegate _next;
static ILogger<ErrorHandlingMiddleware> _logger;
public ErrorHandlingMiddleware(RequestDelegate next,
ILogger<ErrorHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
static async Task HandleExceptionAsync(
HttpContext context,
Exception exception)
{
string error = "An internal server error has occured.";
_logger.LogError($"{exception.Source} - {exception.Message} - {exception.StackTrace} - {exception.TargetSite.Name}");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
error
}));
}
}
Usage :
app.UseMiddleware<ErrorHandlingMiddleware>();
I don't believe this is enough information to go off of, however if you're seeing that 500 error when using the real database and the mock database is working appropriately, I would bet that your issue is with the connection string. You can also check to ensure that you're in the development environment as well.
Update: You can also try to use app.UseDeveloperExceptionPage();

Windows Store Application Place SQLite File in LocalState Folder

I am building a Windows 8 application using sql-net and mvvmcross for data access to a sqlite database. This would be applicable to any Win-8 or Win-Phone app.
I need to install an existing sqlite file on app start.
When using the connection you use syntax such as this
public FlashCardManager(ISQLiteConnectionFactory factory, IMvxMessenger messenger)
{
_messenger = messenger;
_connection = factory.Create("Dictionary.sqlite");
_connection.CreateTable<FlashCardSet>();
_connection.CreateTable<FlashCard>();
}
public void CreateCard(FlashCard flashCard)
{
_connection.Insert(flashCard);
}
That connection creates a file in: C:\Users\USER\AppData\Local\Packages\793fd702-171e-474f-ab3b-d9067c58709b_ka9b83fa3fse2\LocalState
My application uses an existing sqlite database file that I have created. I need to place it in this folder when the application is installed. How would I go about doing this?
Thanks,
JH
Make sure you have the database file you want your app to start off with in one of your apps folders (as in the folders visible in visual studios solution explorer). For this example I'll call this folder "Assets"
All you need to do then is copy this file to the LocalState folder the first time your app runs. This can be done in App.xaml.cs
private async void InitializeAppEnvironment()
{
try
{
if (!(await AppHelper.ExistsInStorageFolder(AppHelper.localFolder, dbName)))
{
StorageFile defaultDb = await AppHelper.installedLocation.GetFileAsync("Assets\\" + dbName);
await defaultDb.CopyAsync(AppHelper.localFolder);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
}
}
I made an AppHelper class to simplify accessing the app data folders, here's the parts I used above:
static class AppHelper
{
public static StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
public static StorageFolder localFolder = ApplicationData.Current.LocalFolder;
public static async Task<bool> ExistsInStorageFolder(this StorageFolder folder, string fileName)
{
try
{
await folder.GetFileAsync(fileName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
}
For a more detailed response on MVVM cross I found the current discussion about cross platform file placement in this discussion: Link
The current thought is that you have to inject platform specific code for this sort of functionality.

Can not move file using file object in adobe air

I have an update utility in adobe air that needs to replace an existing file in application directory. but when I try to move file in application directory it throws IOError describing that file can not be deleted.
I did the following;
protected function onBtnTest(event:MouseEvent):void
{
try
{
service = new File(File.applicationDirectory.nativePath + File.separator +
"assets" + File.separator + "oldFile.exe");
servic_ = new File(File.userDirectory.nativePath + File.separator + "newFile.exe");
servic_.addEventListener(Event.COMPLETE, OnMoveComplete);
servic_.addEventListener(IOErrorEvent.IO_ERROR, OnIOError);
if(service.exists)
servic_.moveToAsync(service, true);
}
catch(err:Error)
{
trace(err.message);
}
}
private function OnMoveComplete(event:Event):void
{
trace("Move Complete.");
trace("File Deleted.");
}
private function OnIOError(event:IOErrorEvent):void
{
trace("OnIOError.");
}
it always execute OnIOError function. but when I try to move same file to some other directory it works fine. How can I do this. Thanks
Just one thing: You CAN'T write into the application directory, it's a flex security.
There is nothing you can do, sorry. Think about using another directory. Personally, I use the application storage directory instead.

Assembly resolving in ASP.NET project outside of bin folder

How can i resolve assemblies references outside of bin folder of ASP.NET web-development server? This can be useful to not have copies of same dll's.
Nothing is working: probing element at web.config don't work, i can't set up domain because it do application manager, and i can't subscribe on the resolve assembly event because it's too late - when i can subscribe initialization is over. So what can i do?
We can use PreApplicationStartMethodAttribute
and mark them some public static void method(in web-project assembly) with no arguments. This can be done at AssemblyInfo.cs class
For example:
[assembly: PreApplicationStartMethod(
typeof(Web.Initializer), "Initialize")]
That method will be called before compilation but after processing of the web.config. So we must explicitly tell to the compiler witch assembly it need to use during compilation. Also we need to subscribe here on Assembly Resolve event so we can manage assemblies resolving. Here is example:
public static class Initializer
{
public static void Initialize()
{
AppDomain.CurrentDomain.AssemblyResolve += LoadFromCommonBinFolder;
var referAsm = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
foreach (var assemblyName in referAsm)
{
try
{
var curAsm = Assembly.Load(assemblyName);
BuildManager.AddReferencedAssembly(curAsm);
LoadChildReferences(curAsm);
}
catch {}
}
}
private static void LoadChildReferences(Assembly curAsm)
{
foreach (var assemblyName in curAsm.GetReferencedAssemblies())
{
try
{
BuildManager.AddReferencedAssembly(Assembly.Load(assemblyName));
}
catch {}
}
}
private static Assembly LoadFromCommonBinFolder(object sender, ResolveEventArgs args)
{
string commonBinFolder = System.Configuration.ConfigurationManager.AppSettings["CommonBinFolderPath"];
if (String.IsNullOrEmpty(commonBinFolder))
{
throw new InvalidOperationException("​​CommonBinFolderPath in the app.config isn't seted.");
}
string assemblyName = new AssemblyName(args.Name).Name;
string assemblyPath = Path.Combine(commonBinFolder, assemblyName);
if (!File.Exists(assemblyPath + ".dll"))
{
if (!File.Exists(assemblyPath + ".exe"))
{
//searching for resources
var ci = CultureInfo.CurrentUICulture;
assemblyPath = Path.Combine(commonBinFolder, ci.Name, assemblyName + ".dll");
if (!File.Exists(assemblyPath))
{
assemblyPath = Path.Combine(commonBinFolder, ci.Parent, assemblyName + ".dll");
if (!File.Exists(assemblyPath))
{
return null;
}
}
}
}
return Assembly.LoadFrom(assemblyPath);
}
}
At this case "Web.Project.Assembly" still must be located in the bin folder. Others assemblies can shared from any folder.
Assemblies that are included under compilation Element in the web.config file must be also in the bin folder or at sub folder with probing element setted.
In same cases we must also add to this code adding references to child assemblies.
Why use 'BuildManager.AddReferencedAssembly'?
In the 'Application_Start' method to bind event the 'AssemblyResolve' and set the Inherits with assembly name in the aspx page,no 'BuildManager.AddReferencedAssembly'.

Track completed downloads from glassfish

I want to be able to track completed downloads served by my glassfish server. I couldn't find a 100% correct solution using servlet life cycle listeners.
Does anyone have a better idea?
Put a try-catch on IOException while serving the file download. If it's thrown, then serving the file download has failed.
E.g. in a custom file servlet:
try {
response.getOutputStream().write(...);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}
Or in a servlet filter which is mapped on the appropriate URL pattern matching file downloads:
try {
chain.doFilter(request, response);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}

Resources