Write into file from assets folder uwp - win-universal-app

I'd like to write text content into a file that is located Assets folder, so I access file but I don't have access to write into it, my code is:
try {
//get the file
StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/test.txt"));
//try to write sring to it
await FileIO.WriteTextAsync(storageFile, "my string");
} catch (Exception ex) {
Debug.WriteLine("error: " + ex);
}
and I get the error:
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
error: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at MyProject.MainPage.<overWriteHtmlSrcFile>d__6.MoveNext()
Have to mention that I need to change this file due app scenario, or maybe is there a way to create this file in public app folder and then move it in assets.

Files located into Assets folder are read only that's why you get this exception. Like you mentioned at the end, there is a method to create your file in a public location, write what you need into it and then just move the file in assets folder. It will be like:
try {
//create file in public folder
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
//write sring to created file
await FileIO.WriteTextAsync(sampleFile, htmlSrc);
//get asets folder
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");
//move file from public folder to assets
await sampleFile.MoveAsync(assetsFolder, "new_file_name.txt", NameCollisionOption.ReplaceExisting);
} catch (Exception ex) {
Debug.WriteLine("error: " + ex);
}

Related

The specified blob does not exist - Download Azure Storage File From Android

I know there are similar questions like this one but none of them worked for me. I am trying to download a file from Azure storage. But I am getting an error and the error message is The specified blob does not exist. But the blob does exist and my connection string is also valid. I am sharing my code below.
It would be helpful if someone can help me out.
Code:
public void downloadFile(ShowContentInfo showContentInfo){
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(() ->{
CloudStorageAccount storageAccount = null;
try {
String dir = "/storage/emulated/0/Download/LmsContents/";
if (!dt.file.folderExists(dir)) {
dt.file.createFolder(dir);
}
storageAccount = CloudStorageAccount.parse(CONNECTION_STRING);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference("containerName");
CloudBlockBlob blockBlob = container.getBlockBlobReference("rblobName");
File file = new File("/storage/emulated/0/Download/LmsContents/" + showContentInfo.getContentTitle());
blockBlob.downloadToFile("/storage/emulated/0/Download/LmsContents/" + showContentInfo.getContentTitle());
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (StorageException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.post(() -> {
Toast.makeText(context, "Successful", Toast.LENGTH_SHORT).show();
});
});
}
One possible reason is that your blob file is not directly under the container. Please check in azure storage via azure portal, see if the blob file is under some subfolders within the container.
If yes(for example, the blob file is b.txt, container name is container111, and subfolder name is sub111), then you should change this line of code
CloudBlockBlob blockBlob = container.getBlockBlobReference("rblobName");
to
CloudBlockBlob blockBlob = container.getBlockBlobReference("sub111\b.txt");
And also, please check the connection string is correct or not.
Check the folder references it seems folder structure which you are providing incorrect. Just see while debugging url is correct or not .

InPlaceHostingManager Hosted in IIS, Access is denied error

I am using the InPlaceHostingManager class to integrate the manifest file for some click once applications hosted in IIS, I am trying to get the version number. See code below
try
{
iphm = new InPlaceHostingManager(new Uri(deployManifestUriStr), false);
iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted);
iphm.GetManifestAsync();
}
catch (UriFormatException uriEx)
{
this._logger.Fatal(uriEx, $"Unable to load Applicaition Versions (Invalid Uri) for uri : {deployManifestUriStr}");
}
catch (PlatformNotSupportedException platformEx)
{
this._logger.Fatal(platformEx, $"Unable to load Applicaition Versions (Platform Not Supported Exception) for uri : {deployManifestUriStr}");
}
catch (ArgumentException argumentEx)
{
this._logger.Fatal(argumentEx, $"Unable to load Applicaition Versions (Argument Exception) for uri : {deployManifestUriStr}");
}
catch (UnauthorizedAccessException ex)
{
this._logger.Fatal(ex);
this._logger.Fatal(ex.InnerException);
this._logger.Fatal(ex, $"Unable to load Applicaition Versions (Unauthorized Access Exception) for uri: {deployManifestUriStr}");
}
catch (Exception ex)
{
this._logger.Fatal(ex, $"Unable to load Applicaition Versions (Exception) for uri : {deployManifestUriStr}");
}
I am getting the following error
System.UnauthorizedAccessException: Access to the path 'Deployment' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)
at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)
at System.Deployment.Application.SubscriptionStore..ctor(String deployPath, String tempPath, ComponentStoreType storeType)
at System.Deployment.Application.SubscriptionStore.get_CurrentUser()
at System.Deployment.Application.DeploymentManager..ctor(Uri deploymentSource, Boolean isUpdate, Boolean isConfirmed, DownloadOptions downloadOptions, AsyncOperation optionalAsyncOp)
at System.Deployment.Application.InPlaceHostingManager..ctor(Uri deploymentManifest, Boolean launchInHostProcess)
at Logging.ApplicaitionVersionManifestHelper.Read(String deployManifestUriStr) in
The applicaition pool is running as network service. Does anyone know where the Deployment folder is?
I had a look inside InPlaceHostingManager > DeploymentManager > SubscriptionStore > Get_CurrentUser (CurrentUSer) I Found the following
public static SubscriptionStore CurrentUser
{
get
{
if (_userStore == null)
{
lock (_currentUserLock)
{
if (_userStore == null)
{
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string deployPath = Path.Combine(folderPath, "Deployment");
string tempPath = Path.Combine(Path.GetTempPath(), "Deployment");
_userStore = new SubscriptionStore(deployPath, tempPath, ComponentStoreType.UserStore);
}
}
}
return _userStore;
}
}
After copying the code to some where I could debug it, I found the following.
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
The above line returns nothing. This lead me to the following
Stackoverflow Post
This change fixed it for me
Open your %WINDIR%\System32\inetsrv\config\applicationHost.config and look for <applicationPoolDefaults>. Under <processModel>, make sure you have the following attributes loadUserProfile="true" setProfileEnvironment="true"
You can use Process Monitor to see which is the Deployment folder.
About how to use the Process Monitor you can refer to this link:
Process Monitor

Calling Azure IoT File Upload from Android KitKat is returning BAD_FORMAT

I am trying to upload a .png file to Azure IoT Hubs, but for some reason I am constantly getting BAD_FORMAT. I am using com.microsoft.azure.sdk.iot:iot-device-client:1.14.2 library as I need to using an android device that is quite old (KitKat version).
The code I am using:
public void btnFileUploadOnClick(View v) throws URISyntaxException, IOException
{
Log.i("IoT App","Uploading file to IoT Hub...");
EditText text = (EditText)findViewById(R.id.editTextFileName);
String fullFileName = text.getText().toString();
try
{
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory, "payments.json");
InputStream inputStream = new FileInputStream(file);
long streamLength = file.length();
if(file.isDirectory())
{
throw new IllegalArgumentException(fullFileName + " is a directory, please provide a single file name, or use the FileUploadSample to upload directories.");
}
else
{
client.uploadToBlobAsync("payments", inputStream, streamLength, new FileUploadStatusCallBack(), null);
}
Log.i("IoT App","File upload started with success");
Log.i("IoT App","Waiting for file upload callback with the status...");
}
catch (Exception e)
{
Log.e("IoT App","Exception while sending event: " + e.getMessage());
}
}
protected class FileUploadStatusCallBack implements IotHubEventCallback
{
public void execute(IotHubStatusCode status, Object context)
{
Log.i("IoT App","IoT Hub responded to file upload operation with status " + status.name());
TextViewControl.log("IoT Hub responded to file upload operation with status " + status.name());
}
}
I have the file payments.json in the device (emulator).
Any help would be appreciated!
It seems I just needed to import a separate library for accessing blob storage. Had to add the following to my gradle script:
implementation 'com.microsoft.azure.android:azure-storage-android:2.0.0'

Check If File Exists, Download and Save File in J2ME

I want to edit my question.
If file still not exist, download and save it, that my case.
To check if file exist, I've try by this code
private boolean isXmlFileExist(){
try{
FileConnection fCon = (FileConnection) Connector.open("file:///"+Resource.XML_PATH + "/" + Resource.XML_FILENAME, Connector.READ);
return fCon.exists();
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
In my resource class
public static final String XML_PATH = "/xml";
public static final String XML_FILENAME = "template.xml";
I have create 'xml' folder under res folder and i have put file 'template.xml' there. But this code always return false.
Whether we can not use the res folder? So, what is the correct path.
Files under res folder are always available because they are packaged with the class files. So, you do not need to check with FileConnection if they exist.
To access these files you can use Class.getResourceAsStream.
For example:
private InputStream open (String fileName) {
return getClass().getResourceAsStream(fileName);
}
// call it like this
open(Resource.XML_PATH + "/" + Resource.XML_FILENAME);

Loading screen in j2me

I want loading screen in my application such that it appear when the internet connection starts and loading screen get hide when I got the data from webservice.
I had tried to use .gif file. It is working properly in the simple application which I made which shows only .gif file. But when I integrate this code with my applicationj it is showing the error.
The error is:
TRACE: <at java.lang.IllegalArgumentException>, Exception caught in Display class
java.lang.IllegalArgumentException
at javax.microedition.media.Manager.createPlayer(), bci=8
at com.semaphore.GifCanvas.<init>(GifCanvas.java:41)
at com.semaphore.CompanySplashScreen.dismiss(CompanySplashScreen.java:89)
at com.semaphore.CompanySplashScreen.keyPressed(CompanySplashScreen.java:78)
at javax.microedition.lcdui.CanvasLFImpl.uCallKeyPressed(), bci=19
at javax.microedition.lcdui.DisplayableLFImpl.uCallKeyEvent(), bci=146
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=30
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:619)
the code which i am using to for executing .gif file is:-
InputStream ins = getClass().getResourceAsStream("/loading.gif");
try {
player = Manager.createPlayer(ins, "image/gif");
player.prefetch();
player.setLoopCount(10);
player.start();
} catch (IOException ex) {
ex.printStackTrace();
} catch (MediaException ex) {
ex.printStackTrace();
}
if ((vidc = (VideoControl) player.getControl("VideoControl")) != null)
vidc.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
vidc.setDisplayLocation(2, 2);
vidc.setDisplaySize(getWidth()/2,getHeight()/2);
}
catch (MediaException me) {}
vidc.setVisible(true);
How can I resolve this?
According to the documentation, your InputStream is null.
Check if you have your resource properly placed. With that path, it should be on the root dir of your project (or the src dir, I'm not sure). But just check it.

Resources