FileConfigurationProvider FileNotFoundException - .net-core-3.1

I'm trying to load ini file with IniConfigurationProvider like this (using net core 3.1)
var config = #"D:\config.ini";
Console.WriteLine(File.Exists(config)); //true
var configProvider = new IniConfigurationProvider(
new IniConfigurationSource() {
Path = config
}
);
configProvider.Load();
but it throws FileNotFoundException
Unhandled exception. System.IO.FileNotFoundException: The configuration file 'D:\config.ini' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at MyProgram.Program.ThreadProc() in d:\apps\Program.cs:line 39
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
File.Exists prints true, so why is it throughing the exception then?

I assume it is a bug because the stream overload works correctly
configProvider.Load(File.OpenRead(config));

IniConfigurationSource doesn't support full path to config file. You must use only file name. And add file provider.
var configProvider = new IniConfigurationProvider(
new IniConfigurationSource() {
Path = "config.ini",
FileProvider = new PhysicalFileProvider("D:\\")
}
);
configProvider.Load();

Related

xamarin for android throws NullReferenceException when trying to request location updates

I can't seem to figure out, why is this causing an exception.
GPSListener gps = new GPSListener(); // <- implements ILocationListener interface
(LocationManager)GetSystemService(LocationService).RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, gps); // <- System.NullReferenceException
Calling IsProviderEnabled for the "gps" provider returns true.
GetSystemService does also return a valid LocationManager and not a null. gps object is also not null. ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION are also added to the manifest.
The call stack
at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12
at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V (_JniMarshal_PP_V callback, System.IntPtr jnienv, System.IntPtr klazz) [0x0001c] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:23
at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(intptr,intptr)
The internal exception message is "Object reference not set to an instance of an object."
How can i find out more information what is actually not set in this situation. And how could i fix it. The error happens both in emulator (API 30) and physical phone with Android 7.
Please make sure your app has been granted the permission about the location by the user, not only declare it in the AndroidManifest.xml. And you can add the following code into the oncreate method of the activity to do that.
var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
In addition, if you call the method in the background service, you need to add the ACCESS_BACKGROUND_LOCATION in the AndroidManifest.xaml and use the following code:
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();

File.Delete() throw "owner died" in Xamarin

Generally, file deletion can be performed correctly on most Android phones
However, when I run this line of code on "Huawei art-al00x (Android 10.0 - API 29)", the operation throws an exception "owner died"
I can create files and write data, but I can't delete files
I've never been in this situation before
After Google searched, there is still no result
After the second test, I found that if I checked the file in the file manager, I could delete it smoothly, while if I didn't check the file, it would throw an exception
The Code:
string path = "Want Save Path";
byte[] buffer = new uint8_t[73790];
using (BinaryWriter BW = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
BW.Write(buffer, 0, (int)exer.Size);
BW.Flush();
BW.Close();
Console.WriteLine("USM:Save Image Data Success");
}
StackTrace:
at System.IO.FileSystem.DeleteFile (System.String fullPath) [0x00065]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs:215
at System.IO.File.Delete (System.String path) [0x0000e]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:107
at DebugTest.MyView.MainPage_OperateView.TTTFrame_Click () [0x00014]
in G:\VS2019 Projects\DebugTest\DebugTest\DebugTest\MyView\MainPage_OperateView.xaml.cs:263

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

handle some errors in Global.asax

I have a web application on .NET4 and MVC3 (razor) .
I want to handle my application errors in Global.asax. I have created application_error function.
I have noticed and found some errors.
one of them returns this string in Application_Error when I am trying to add break point on line Response.Clear(); and that error is generic.
how can I find which codes or part of my codes makes it?
my code:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
}
error on httpException:
{System.Web.HttpException (0x80004005): File does not exist.
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String
physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String
overrideVirtualPath)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context,
AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt
ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)}
i found the solution
string errorLocation = Request.Path;
this syntax in Application_Error() tel you where is the problem :)
Just to state my experience with this exception, in my case the reason was that there was no webpage specified as the start page for the site.

Having a issue processing multiple files at once in a Windows Service with a FileSystemWatcher

When I try and process more than a couple of files at the same time (they are created and dumped in a folder at the same time), my service dies.
When I wasn't trying to use a thread and had all the processing (where the code in the ProcessFiles method now is) in the Watcher_Created event, at least one file gets through successfully.
When I added the threading (which I'm pretty sure I have to do for this, but am totally unsure of the exact flow and syntax using the threading), I get the following msg in my ProcessFiles method:
System.ArgumentException: Empty path name is not legal.
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
The above msg occurs on the using line:
private static void ProcessFiles()
{
try
{
Thread.Sleep(500);
GetCruiseLineShipName(fullFileName, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
which is obvious, because the "fullFileName" is an empty string. However, it does get set in the Watcher_Created event:
private static void Watcher_Created(object sender, FileSystemEventArgs e)
{
fullFileName = e.FullPath;
}
So, I don't understand why the fullFileName variable is an empty string. I know it must have something to do with the threading I'm trying.
My OnStart event looks like this:
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\DropOff_FTP\MIS");
Watcher.EnableRaisingEvents = true;
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Filter = "*.txt";
Watcher.IncludeSubdirectories = false;
Watcher.InternalBufferSize = 64;
Thread t = new Thread(new ThreadStart(ProcessFiles));
t.Start();
}
Can someone PLEASE inform me how I can use the FileSystemWatcher to process multiple files that are dumped in there at the same time. If I need to use threading, could you please supply how I would use the thread based on the code above?
btw, I'm using the 4.0 framework.
Conceptually something is wrong here. If I understand you correctly, you have two files created in the same folder with short time difference. Then you receive the first event and set the name of ONE file in the global variable fullFileName and you expect that the running thread process this file using the global variable, but in the same time another event Created happens and you change the global variable that the separate thread is processing
I will try to change you code in this way:
the OnStart method loose the code that starts the Thread
the Watcher_Created event will start the thread passing the name of the file that raised the event
.....
Thread t = new Thread(ProcessFiles);
t.Start(e.FullPath);
.....
the ProcessFiles receive the argument with the name of the file to process...
public void ProcessFiles(object argument)
{
string fullFileName = (string)argument;
GetCruiseLineShipName(fullFileName, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(fullFileName, ....))
.....
}

Resources