I am currently working on a program on WinForms on Visual Studio Community 2022. The program has to check if a file exists on the install directory using File.Exists(), but there is a really weird behaviour that I cannot seem to solve: when debugging (and even running it in the Release mode) the application on VS2022, the value the method returns is false (which is right, because the file doesn't exist at the moment of running the method), but when installing the application, it says the file exists, even when it doesn't, and it can even read the content of that file. Here's the code:
private static string AppPath = $#"{Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)}\eMA\eMA";
public async Task<JArray> GetVersionsJArrayFromComputer()
{
JArray versionsJArray = new JArray();
await Task.Run(async () =>
{
string path = AppPath;
if (!await CheckIfVersionJSONFileExists())
{
if (!await IsRunningAsAdmin())
{
await RunAsAdmin();
Environment.Exit(0);
}
else
{
await SaveVersionJSONFile(await SetVersionsJArrayFromComputer());
}
}
string versionFilePath = $#"{path}\version.json";
string versionFile = File.ReadAllText(versionFilePath);
versionsJArray = (JArray)JsonConvert.DeserializeObject(versionFile);
});
return versionsJArray;
}
private static async Task<bool> CheckIfVersionJSONFileExists()
{
bool fileExists = false;
await Task.Run(() =>
{
string path = AppPath;
string fileName = $#"{path}\version.json";
fileExists = File.Exists(fileName);
});
return fileExists;
}
I created some MessageBoxes to try to debug the application when it is already installed, and this is what it says:
This is the content that it reads from the file (and, in theory, if the file doesn't exist, it shouldn't have any content):
And I don't really know why would it say the file doesn't exist when debugging and then it exists when installed. Any help would be really appreciated.
Related
After some advise around calls to firebase storage primarily how (from a sync POV) I should be checking to see if a file exists.
To set the context I am reading in a state file as json using the DownloadCoroutine function below and passing this into a JsonTextReader, this is working fine as long as the file exists in the first place (which as a new user it will not).
So then I wrote the below checkIfFile exists function which also works in a standalone capacity (Grabs the URL to prove that this file does in fact exist). Once this function has completed I then set a bool (SaveFileExists) to say this is/is not an existing file then go create one dependent on the state.
Where my problem lies is the order in which these functions are executed, I need the check to happen before any other methods are executed, they are both called in the LoadScene function currently. What I think I need to do is make the check an Async method returning a task? If so how would this look and where should I be calling it from, I have tried this but I think it keeps locking the main thread.
So the state right now is that because that bool doesnt change in time, the download of the storage file doesnt happen and the Json is never read in and throws an error, at the end of the console output the checkfile URL is outputted, any help would be great ,thanks.
private IEnumerator DownloadCoroutine(string path)
{
var storage = FirebaseStorage.DefaultInstance;
var storageReference = storage.GetReference(path);
if (SaveFileExists == true)
{
var DownloadTask = storageReference.GetBytesAsync(long.MaxValue);
yield return new WaitUntil(predicate: () => DownloadTask.IsCompleted);
byte[] fileContents = DownloadTask.Result;
retrievedSaveFile = Encoding.Default.GetString(fileContents);
Debug.Log("Downloading the save file");
}
else
{
createNewSaveFile(path);
}
}
Check to see if the Json file exists
private void CheckIfFileExists(string path)
{
var storage = FirebaseStorage.DefaultInstance;
var storageReference = storage.GetReference(path);
storageReference.GetDownloadUrlAsync().ContinueWith(task => {
if (!task.IsFaulted && !task.IsCanceled) {
Debug.Log("Download URL: " + task.Result);
SaveFileExists = true;
}
else{
Debug.Log("file doesnt exist so we create one");
}
});
}
Load scene
public IEnumerator LoadLastScene()
{
var User = FirebaseAuth.DefaultInstance.CurrentUser;
Debug.Log("USERID IS " + User.UserId.ToString());
CheckIfFileExists("Saves://" + User.UserId.ToString() + "saveFile.json");
yield return DownloadCoroutine("Saves://" + User.UserId.ToString() +
"saveFile.json");
}
The things you have to do is that
User authentication
Everything must be inside an async task function
check if the file exists
await storageRef.Root.Child(fUser.UserId).Child("Data").GetDownloadUrlAsync().ContinueWith(async task2 =>
{
if (task2.IsFaulted || task2.IsCanceled)
{
Debug.Log("<color=Red>File Not Exists</color>");
}
else
{
Debug.Log("<color=green>File Exists</color>");
await DownloadData();
}
});
I'm relatively new to software development for the Hololens 2 and have a pretty big problem I've been messing around with for a long time and I'm slowly running out of ideas.
My project looks like this. I've written a Unity application to capture data and store it in a database (sqlite). A Xamarin.Forms UWP application is supposed to take the data from the database and use it to paint charts for better visualisation. The big problem is, both apps need to be able to access the same database on the Hololens 2. I thought that I could be the database on a usb stick and both apps could access the usb stick. In the Xamarin app and in the Unity app "removable storage" is enabled. In the Xamarin App I have made the file extension known under Appmanifest declaration. I am trying to get the connection with the following commands:
namespace ARScoliosis.XamarinApp.UWP.Services
{
public class DatabasePath : IDatabasePath
{
public async Task<string> GetLocalFilePath()
{
var messageDialog = new MessageDialog("No Usb connection has been found.");
StorageFolder externalDevices = KnownFolders.RemovableDevices;
if(externalDevices == null)
{
messageDialog.Commands.Add(new UICommand("No Devices", null));
}
StorageFolder usbStick = (await externalDevices.GetFoldersAsync()).FirstOrDefault(); <---According to debugging it stops here and jumps to optionsBuilder.UseSqlite($"Filename={databasePath}");
if (usbStick == null)
{
messageDialog.Commands.Add(new UICommand("No UsbStick", null));
}
var usbStickFolder = await usbStick.CreateFolderAsync("DB", CreationCollisionOption.OpenIfExists);
if (usbStickFolder == null)
{
messageDialog.Commands.Add(new UICommand("No Folder", null));
}
var file = await usbStickFolder.CreateFileAsync("Database.db", CreationCollisionOption.OpenIfExists);
if(file == null)
{
messageDialog.Commands.Add(new UICommand("No File", null));
}
//var success = await Launcher.LaunchFileAsync(file);
return file.ToString();
}
My dbcontext file looks something like this:
namespace XamarinApp.Authentication
{
public partial class DBContext : DbContext
{
public DBContext()
{
this.Database.EnsureCreated(); <--- Microsoft.Data.Sqlite.SqliteException: "SQLite Error 14: 'unable to open database file'."
this.Database.Migrate();
}
public virtual DbSet<ItemData> ItemDatas { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var databasePath = DependencyService.Get<IDatabasePath>().GetLocalFilePath();
optionsBuilder.UseSqlite($"Filename={databasePath}");
}
}
namespace XamarinApp.Helpers
{
public interface IDatabasePath
{
Task<string> GetLocalFilePath();
}
}
Unfortunately this code does not find the Usb stick on the Hololens, i think. When I look in file explorer, I see the stick with all its data. In the Unity App, the stick is also not found, although I use the same code here, only slightly modified.
Does anyone know where my error lies, why I can't access the USB stick with either of the two apps? Has anyone tried something similar and knows how to do it?
i would like to thank you in advance for your help.
Thank you very much.
****Hi Hernando - MSFT,
Please excuse my late reply. i had somehow forgotten. I have found a way where I can find my database on the usb stick.
public static async Task<string> GetUsbStick()
{
StorageFolder UsbDrive = (await Windows.Storage.KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault();
if (UsbDrive == null)
{
throw new InvalidOperationException("Usb Drive Not Found");
}
else
{
IReadOnlyList<StorageFile> FileList = await UsbDrive.GetFilesAsync();
var Path = UsbDrive.Path.Replace('\\','/');
foreach (StorageFile File in FileList)
{
var DBFound = File.Name.Contains("test.db");
if (DBFound == true)
{
return Path + File.Name;
}
}
throw new InvalidOperationException("DataBaseNotFound");
}
}
There I get the exact path for the database output. Only that somehow brings nothing. I cannot open it in the next step. "Sqlite cant open database" it says.
public static async Task<int> Init()
{
try
{
DatabasePath = await GetUsbStick();
StrConnDatabase = "Data Source" + "=" + DatabasePath + ";Mode=ReadWrite;";
}
catch (Exception io)
{
IsInit = false;
throw new InvalidOperationException(io.Message);
}
finally
{
//Try to Open Database to Read
using (var db = new Microsoft.Data.Sqlite.SqliteConnection(StrConnDatabase))
{
try
{
db.Open(); //<- here it breaks off
db.Close();
IsInit = true;
}
catch (Exception io)
{
throw new InvalidOperationException(io.Message);
}
}
}
return 1; // Succes
}
What could be the reason that this does not work?
is there a way to create a working copy within the app, which is then written back to the usb stick?
KnownFolders.RemovableDevices doesn't be supported on the HoloLens, for more information please see:Known folders. It is recommended to take a try at File pickers to pick one file manually.
I am pretty new in WindowsPhone applications development. I am currently developing a Unity application for Windows Phone 8.0. Inside this app I would like to open a PDF using the appropriate application on the phone (Acrobat Reader, Windows Reader, etc...)
First, I tried this :
void PDFButtonToggled(bool i_info)
{
Dispatcher.BeginInvoke(() =>
{
DefaultLaunch();
});
}
async void DefaultLaunch()
{
// Path to the file in the app package to launch
string PDFFilePath = #"Data/StreamingAssets/ImageTest.jpg";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(PDFFilePath);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
throw new Exception("File launch failed");
}
}
else
{
throw new Exception("Could not find file");
}
}
It returned me an exception so I searched why. I found that topic (written in 2013 :/) about async functions / threads : LINK. To sumarize, here the answer of Unity staff :
It will only work on Windows Store Apps, and you'll have to wrap the code in #if NET_FX/#endif. On other platforms, you cannot use async/.NET 4.5 code in scripts. If you want to use it for windows phone, you'll have to write that code in separate visual studio solution and compile it to DLL, so unity can use it as a plugin.
So I decided to create the double DLL solution described in the Unity Manual here : LINK. But when I complete the class of the first DLL with the "async void DefaultLaunch()" function given above I don't have references about Windows.ApplicationModel.etc... and Windows.System.etc... .
And here I am, a little bit lost between WP, Unity, 8.0 apps, StoreApps, etc...
If anyone has advices, questions, anything that can help me, it's welcome. :)
Crèvecoeur
I found a solution by myself but on a WindowsPhone8.1 application.
Here it is :
async void PDFButtonToggled(bool i_info)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
DefaultLaunchFile();
});
}
async void DefaultLaunchFile()
{
StorageFolder dataFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data");
StorageFolder streamingAssetsFolder = await dataFolder.GetFolderAsync("StreamingAssets");
// Path to the file in the app package to launch
string filePath = "PDFTest.pdf";
var file = await streamingAssetsFolder.GetFileAsync(filePath);
if (file != null)
{
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
throw new Exception("File launch failed");
}
}
else
{
throw new Exception("File not found");
}
}
I'm writing my first Windows Phone 8 app, and I'm just trying something simple. Read / Write file. Here's my two methods:
public static async Task<Week> Load()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
try
{
StorageFile mealsFile = await folder.GetFileAsync("file.txt");
if (mealsFile != null)
{
using (var stream = await mealsFile.OpenAsync(FileAccessMode.Read))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
var w = (List<MyTypeHere>)serializer.ReadObject(stream.AsStreamForRead());
if (w != null)
MyWeek.WeekList = new ObservableCollection<MyTypeHere>(w);
}
}
}
catch(FileNotFoundException fEx)
{
MyWeek = new Week();
}
return MyWeek;
}
public static async Task<bool> Save()
{
try
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile mealsFile = await folder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting);
using (var stream = await mealsFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var sw = stream.GetOutputStreamAt(0))
{
var serializer = new DataContractSerializer(typeof(List<MyTypeHere>));
serializer.WriteObject(sw.AsStreamForWrite(), MyWeek.WeekList.ToList());
await sw.FlushAsync();
}
}
MyWeek = null;
return true;
}
catch(Exception ex)
{
return false;
}
}
I'm calling the Save (with breakpoint it works fiine), then call Load (with breakpoint) which load the file, the file exists and it populate my object graph.
When I close the app and restart it, the catch of the FileNotFoundException is caught. Why?
From what I can see the Local Folder is supposed to be persisting the file. What I'm missing that obviously should be obvious...
Thanks
Edit:
I'm using the Windows Phone emulator, and when I close it and hit F5 on Visual Studio, the file is not there anymore.
Apparently by closing the emulator, the files in Local Storage are lost, thanks to #cdndevs via Twitter. I was closing the emulator each time I was stopping debugging instead of letting the emulator simply "stay" there between restart.
By stopping debugging and restarting the app without closing the emulator, the files are there. Well, not super intuitive I must admit, or it might just be me. Hope that help other people like me ;).
Hi everyone I'm trying to upload .csv file in amazon S3 it works fine till one file was uploaded, but after then system hangs and nothing will happen next.
I was refer this but not get right solution.
If you have right way then please let me aware.
My code is her
public static void UploadScreenShot(string FullFilePath, string DestPath, string FileName)
{
try
{
TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.USEast1));
fileTransferUtility.Upload(FullFilePath, existingBucketName, DestPath +FileName);
fileTransferUtility.Dispose();
}
catch{}
}
I am having this on AWS SDK 2.3, it works fine on AWS SDK 2.2.2. I still havn't figured out why its locking up.
I locks up in this method on line
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
executionContext.RequestContext.Metrics.AddProperty(Metric.AsyncCall, true);
try
{
executionContext.RequestContext.Metrics.StartEvent(Metric.ClientExecuteTime);
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
return response;
}
finally
{
executionContext.RequestContext.Metrics.StopEvent(Metric.ClientExecuteTime);
this.LogMetrics(executionContext);
}
}
I ended up filing a bug on their github. https://github.com/aws/aws-sdk-net/issues/137