#ionic-native/zip not working on API 31, open failed: EACCES (Permission denied) - ionic-framework

I am working on a legacy ionic-cordova project, running my android app on API level 31 (upgraded recently).
I have android:requestLegacyExternalStorage="true" and the permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
on my AndroidManifest.xml file. Also checked my permissions with 'cordova-plugin-android-permissions' and also 'cordova-diagnostic-plugin' for 'READ_EXTERNAL_STORAGE' & 'WRITE_EXTERNAL_STORAGE' permissions and got granted: true,
But I still can not use the 'cordova-plugin-zip', due to EACCES (Permission denied),
this is the error I get on Android Studio:
2023-01-11 13:06:36.328 14977-22760/es.my-app.my-app E/Zip: An error occurred while unzipping.
java.io.FileNotFoundException: /storage/emulated/0/Download/some-file.KMZ: open failed: EACCES (Permission denied)
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileInputStream.<init>(FileInputStream.java:160)
at java.io.FileInputStream.<init>(FileInputStream.java:115)
at org.apache.cordova.CordovaResourceApi.openForRead(CordovaResourceApi.java:250)
at org.apache.cordova.CordovaResourceApi.openForRead(CordovaResourceApi.java:233)
at org.apache.cordova.Zip.unzipSync(Zip.java:84)
at org.apache.cordova.Zip.access$000(Zip.java:23)
at org.apache.cordova.Zip$1.run(Zip.java:39)
Previews to the update, the Zip.unzip method from '#ionic-native/zip' used to work fine to decompress my .kmz files, but now it throws an error: -1 due to permissions denied while trying to read from the External Storage.

Finally, I came up with an OK solution, starting from API 31, to have full access to the external storage there is a particular permission: 'MANAGE_EXTERNAL_STORAGE', in order to register my app for that permission, firstly I had to add it to the 'config.xml' file like so:
<widget xmlns:android="http://schemas.android.com/apk/res/android">
<platform name="android">
...
<config-file parent="/manifest" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
</config-file>
...
</platform>
</widget>
it is important to add xmlns:android="http://schemas.android.com/apk/res/android" at the widget tag.
Then to request the 'MANAGE_EXTERNAL_STORAGE' permission I modified the .java file of the plugin on android studion like so:
...
public class FileChooser extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R && !android.os.Environment.isExternalStorageManager()) {
try {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", cordova.getContext().getPackageName(), null);
intent.setData(uri);
cordova.getActivity().startActivity(intent);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
cordova.getActivity().startActivity(intent);
}
}
.... plugin code ...
}
}
The execute function is the starting point of execution for the plugin, there, I added the code that requests permission before executing the rest of the plugin processes...
NOTE: with the newer scoped stotage restrictions for android the 'MANAGE_EXTERNAL_STORAGE' permission might make it hard to publish your app on play store, there are other, more complex, strategies to access the external storage that will not cause that trouble.

Related

Flutter facebook app events : lateinit property anonymousId has not been initialized

I'm trying to call Facebook app events in my flutter project.
I'm using the dependency facebook_app_events: ^0.12.0.
meta-data is also added in the manifest file.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
void callFBEvent() async {
try {
var i = await facebookAppEvents.getAnonymousId();
await facebookAppEvents.setAdvertiserTracking(enabled: true);
await facebookAppEvents.logEvent(
name: "User_Selection_Screen", parameters: {
"User_Selection": "User_Selection",
});
print("facebook event success User_Selection_Screen");
}catch(e){
print(e);
}
}
Getting below error
kotlin.UninitializedPropertyAccessException: lateinit property anonymousId has not been initialized
at id.oddbit.flutter.facebook_app_events.FacebookAppEventsPlugin.handleGetAnonymousId(FacebookAppEventsPlugin.kt:82)
at id.oddbit.flutter.facebook_app_events.FacebookAppEventsPlugin.onMethodCall(FacebookAppEventsPlugin.kt:55)
at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:84)
at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:822)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
I open the project in an android module. Then just clean the build of the project first and then just build and sync the Gradle in the android module. then the issue was solved. But I already use pub get lots of time before that but that didn't work. fine, my issue was solved.
In my case the problem was that I inserted the the meta data under actvity tag instead of inserting that under application tag
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
So the solution was basically to put the :
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken"
android:value="#string/facebook_client_token"/>
in the right spot , they need to be under the application Tag , in the first range so not under appliction and then activity tag just under the application tag in the androidManifest just as in the pic below !
enter image description here

MediaScannerConnection fails on Android 6 because of permission denial

I use a MediaScannerConnection to call its scanFile method, for adding images to device gallery. But in Android 6 I receive this exceptions when I execute it:
E/DatabaseUtils: java.lang.SecurityException: Permission Denial:
reading com.android.providers.media.MediaProvider uri
content://media/external/fs_id from pid=22984, uid=10078 requires
android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
and
E/iu.UploadsManager: java.lang.SecurityException: Permission Denial:
reading com.android.providers.media.MediaProvider uri
content://media/external/fs_id from pid=22984, uid=10078 requires
android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
Any help?

ClickOnce Deployment Error: Application improperly formatted... (website install)

I'm trying to deploy a program with ClickOnce. It works fine if I try the "install from CD" Version. If I try to deploy it in the "Install from a website" Version I get following Error if I try to run it:
Cannot continue. The application is improperly formatted. Contact the
application vendor for assistance.
The detailed Error is:
PLATFORM VERSION INFO
Windows : 6.1.7601.65536 (Win32NT)
Common Language Runtime : 4.0.30319.18444
System.Deployment.dll : 4.0.30319.34244 built by: FX452RTMGDR
clr.dll : 4.0.30319.18444 built by: FX451RTMGDR
dfdll.dll : 4.0.30319.34244 built by: FX452RTMGDR
dfshim.dll : 4.0.41209.0 (Main.041209-0000)
SOURCES
Deployment url : https://mywebsite.com/HBAPackageConfig.application
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of https://mywebsite.com/HBAPackageConfig.application resulted in exception. Following failure messages were detected:
+ Exception reading manifest from https://mywebsite.com/HBAPackageConfig.application: the manifest may not be valid or the file could not be opened.
+ For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [2/5/2015 2:13:50 PM] : Activation of https://mywebsite.com/HBAPackageConfig.application has started.
ERROR DETAILS
Following errors were detected during this operation.
* [2/5/2015 2:13:51 PM] System.Deployment.Application.InvalidDeploymentException (ManifestParse)
- Exception reading manifest from https://mywebsite.com/HBAPackageConfig.application: the manifest may not be valid or the file could not be opened.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
--- Inner Exception ---
System.Xml.XmlException
- For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
- Source: System.Xml
- Stack trace:
at System.Xml.XmlCharCheckingReader.Read()
at System.Xml.XsdValidatingReader.Read()
at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.
I tried to sign the application in Visual Studio but I still get this Error.
Has anybody a solution for my why this is not working? I tried in Chrome and IE.
You may need to allow access to the Install folder. ClickOnce opens a new connection to the Install folder. So, even if you have access to the folder the new connection cannot access the components, for example the manifest.
In the example below, and just for brevity, open access is granted to MyInstallPath:
<runtime>
<location path="MyInstallPath">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</runtime>

FluentMigrator create table permission denied

I'm running
C:\Dev\Migrate> MSBuild.exe .\build.proj /t:Migrate
from powershell on a fluentmigrate project
And getting the following error :
!!! An error occured executing the following sql:
CREATE TABLE [dbo].[VersionInfo] ([Version] BIGINT NOT NULL)
The error was CREATE TABLE permission denied in database 'H2H'.
Here is the build.proj
<?xml version="1.0"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
DefaultTargets="Migrate" ToolsVersion="4.0">
<PropertyGroup>
<MigratorTasksDirectory>$(MSBuildProjectDirectory)\..\EqulibriumMarkets\packages\FluentMigrator.Tools.1.1.2.1\tools\AnyCPU\40\</MigratorTasksDirectory>
<MainProjectDirectory>$(MSBuildProjectDirectory)</MainProjectDirectory>
<ConnectionString>******************************</ConnectionString>
</PropertyGroup>
<UsingTask
TaskName="FluentMigrator.MSBuild.Migrate" AssemblyFile="$(MigratorTasksDirectory)FluentMigrator.MSBuild.dll" />
<Target Name="Migrate">
<Message Text="Starting FluentMigrator migration" />
<!-- Important: Target must be your Migrations assembly name, not your dll file name -->
<Migrate Database="SqlServer2012"
Connection="$(ConnectionString)"
Target="$(MSBuildProjectDirectory)/bin/debug/EQ.DbMigration.dll" />
</Target>
</Project>
Shouldn't permissions be taken form the connection string user details? connecting as db owner?
Shouldn't permissions be taken form the connection string user
details? connecting as db owner?
To find out, check your application event log for an entry around the time this occurs. The event entry should also contain the user name that is being denied permission.

IISExpress 8 with custom configuration file - web service won't load

When I develop a WCF service or website solution, I always use IISExpress with a custom configuration file so I can share the setup with other developers in the team. Basically, I run a batch file with the following command in it:
"C:\Program Files (x86)\IIS Express\iisexpress.exe" /config:service-hosts.config
Where service-hosts.config is the path to my custom configuration file.
This method has been working perfectly fine, and still works fine in other solutions on my PC (each with their own service-hosts.config file). However, I've just started having a problem loading a WCF service using this method. I'm getting the following error when trying to browse to the service root dir, or any of the built in help endpoints:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information:
Module IIS Web Core
Notification Unknown
Handler Not yet determined
Error Code 0x80070003
Config Error Cannot read configuration file
Config File \?\D:\Projects\MyProject\WCFSite\web.config
Requested URL http:// localhost:80/
Physical Path
Logon Method Not yet determined
Logon User Not yet determined
Request Tracing Directory C:\Users\Spikeh\Documents\IISExpress\TraceLogFiles\
Config Source:
-1:
0:
More Information:
This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error.
If you see the text "There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined", this error is because you are running a .NET Framework 3.5-based application in .NET Framework 4. If you are running WebMatrix, to resolve this problem, go to the Settings node to set the .NET Framework version to ".NET 2". You can also remove the extra sections from the web.config file.
View more information ยป
I've been debugging for hours and can't get this error to change, let alone fix it.
I've tried overwriting my service-hosts.config file with a few different versions of applicationHosts.config, running IISExspress in 64bit, replacing the web.config file with a very basic version, setting permissions on the directory (to the point where every user on my PC has access), and changing the app pool, but still no change.
The weird thing is... when I change the WCF project to use "IISExpress" in the Web section of project properties, then subsequently debug the project, everything works fine... even with all of my web.config settings in place.
This points to how I'm running IISExpress, or my service-hosts.config file... though the service-hosts.config file (with slight modifications for the sites involved) is exactly the same as it is in my other projects.
One thing to note (might be a red herring), but I did downgrade the solution from VS2012 to VS2010, and changed the framework target to .Net 4.0... not sure if something might be configured funny due to that?
Does anyone have any ideas? I'm at the point of jumping off the roof...
UPDATE:
Here's the debug information from IISExpress (running with /trace:e):
Running IIS...
Starting IIS Express ...
Initializing the W3 Server Started CTC = 5514916
PreInitSitesThread: Premature Exit Occured ( hr = 80070003 )
W3 Server initializing WinSock. CTC = 5514916
W3 Server WinSock initialized. CTC = 5514916
W3 Server ThreadPool initialized (ipm has signalled). CTC = 5514916
Start listenerChannel http:0
Successfully registered URL "http://*:80/" for site "MyWebsite" application "/"
Registration completed for site "MyWebsite"
AppPool 'MyCustomAppPool' initialized
InitComplete event signalled
IIS Express is running.
Enter 'Q' to stop IIS Express
IncrementMessages called
Request ended: http://localhost:80/ with HTTP status 500.19
And here's the important part of my service-hosts.config:
<applicationPools>
<add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_BIN%\config\templates\PersonalWebServer\aspnet.config" autoStart="true" />
<add name="Clr4ClassicAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_BIN%\config\templates\PersonalWebServer\aspnet.config" autoStart="true" />
<add name="Clr2IntegratedAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_BIN%\config\templates\PersonalWebServer\aspnet.config" autoStart="true" />
<add name="Clr2ClassicAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_BIN%\config\templates\PersonalWebServer\aspnet.config" autoStart="true" />
<add name="UnmanagedClassicAppPool" managedRuntimeVersion="" managedPipelineMode="Classic" autoStart="true" />
<add name="IISExpressAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_BIN%\config\templates\PersonalWebServer\aspnet.config" autoStart="true" />
<add name="MycustomAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
<applicationPoolDefaults managedRuntimeLoader="v4.0" >
<processModel/>
</applicationPoolDefaults>
</applicationPools>
<listenerAdapters>
<add name="http" />
</listenerAdapters>
<sites>
<site name="MyWebsite" id="1">
<application path="/" applicationPool="MyCustomAppPool">
<virtualDirectory path="/" physicalPath="D:\Projects\MyProject\WCFSite\" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:80:" />
</bindings>
</site>
<siteDefaults>
<logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
<traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
</siteDefaults>
<applicationDefaults applicationPool="Clr4IntegratedAppPool" />
<virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
<webLimits />
Seems that the service-hosts.config file was pointing to something it shouldn't have been pointing to. I replaced my service-hosts.config with an copy from an older project (and therefore an older version of IISExpress / .Net Framework) and everything works fine.
Sounds like it was to do with my 4.5 -> 4.0 downgrade after all.