Move files from applicationStorage to Documents in app - actionscript-3

I've got an app that, since 5 years now, that displays an offline map by reading from a folder embed in it ("assets").
Since Android 11, it's impossible to read from ApplicationStorage (Error #3001: File or directory access denied), so I'm trying to copy the folder from applicationStorage to "Documents".
What I did :
source = File.applicationDirectory.resolvePath("assets/maps");
destination = File.documentsDirectory.resolvePath("Documents/www");
source.addEventListener(Event.COMPLETE, onMapCopyComplete);
source.copyToAsync(destination, false);
function onMapCopyComplete(e: Event): void {
source.removeEventListener(Event.COMPLETE, onMapCopyComplete);
log("onMapCopyComplete()");
}
I've got a return onMapCopyComplete() but when I'm looking in InternalStorage/Documents of my phone I've got the folders but all are empty... None of the files were copy..
PrintScreen computer vs phone
To read the files, here's what I'm doing :
function startMapsView()
{
var indexFile:File = File.applicationStorageDirectory.resolvePath("www/index.html");
if (!indexFile.exists)
{
log("startMapsView() Index file not found, Please check www/index.html");
return;
}
// Create StageWebView
stageWebView = new StageWebView(isMobile); // Set to TRUE for System's NativeWebView, FALSE is for AIR's WebView
stageWebView.stage = stage;
stageWebView.viewPort = new Rectangle(0, iOSStatusBarHeight + headerBarHeight, deviceStageSize.width, deviceStageSize.height - (iOSStatusBarHeight + headerBarHeight + footerBarHeight));
stageWebView.addEventListener(flash.events.Event.COMPLETE, onStageWebViewLoaded);
stageWebView.addEventListener(flash.events.ErrorEvent.ERROR, onStageWebViewError);
stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, onStageWebViewLocationChanging);
// Load Map URL
stageWebView.loadURL(mapsURL);
}
And mapsURL is define by :
function setMapsURL(doNotEnableButtons: Boolean = false): void {
var indexFile: File = File.documentsDirectory.resolvePath("Documents/www/index.html");
trace("indexFile url is = "+indexFile.url);
if (!indexFile.exists) {
log("setMapsURL() Index file not found, Please check www/index.html");
return;
}
var assetsDir: File;
if (!useOnlineMaps) {
assetsDir = new File(destination.resolvePath("index.html").nativePath);
} else {
assetsDir = new File(destination.resolvePath("onlineMaps.html").nativePath);
mySavedData.data.onlineMapChoosen = false;
}
mapsURL = assetsDir.url;
log("setMapsURL() " + mapsURL);
if (!doNotEnableButtons) enableMapButtons();
}

Related

Batch Opening Multiple Revit Model - Dismiss BIM360 Sign In

I have a question about opening Multiple Revit Model in background to perform some batch automation task. These models were downloaded from BIM360 Design collaboration and placed into a folder.
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiapp = commandData.Application;
Document rvtDoc = null;
string[] files = Directory.GetFiles(#"C:\Models", "*.rvt");
foreach (string file in files)
{
ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(Path.GetFileName(file));
if (modelPath != null)
{
OpenOptions openOptions = new OpenOptions();
WorksetConfiguration openConfiguration = new WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets);
openOptions.SetOpenWorksetsConfiguration(openConfiguration);
openOptions.DetachFromCentralOption = DetachFromCentralOption.ClearTransmittedSaveAsNewCentral;
openOptions.Audit = false;
var currentDoc = uiapp.OpenAndActivateDocument(modelPath, openOptions, false);
}
}
return Result.Succeeded;
}
I couldn't skip the Login screen as shown in below images.
Any suggestion will be highly appreciated.
Do you really want to open and activate the document by?
var currentDoc = uiapp.OpenAndActivateDocument(modelPath, openOptions, false);
How about using the following way:
var currentDoc = uiapp.Application.OpenDocumentFile(modelPath, openOptions);

Orientation of Forge viewable generated on Design Automation in Forge Viewer not matching orientation in Inventor

I'm exporting SVFs from a model using the design automation API. With some models, the orientation in the Viewer of the viewable does not match the orientation in Inventor.
How do I correct this so that all models come out with their Viewer orientation matching the input Inventor model?
The following code is where the SVF is exported. A blog post on this functionality would be helpful.
private string SaveForgeViewable(Inventor.Document doc) {
string viewableOutputDir = null;
using(new HeartBeat()) {
//LogTrace($"** Saving SVF");
try {
TranslatorAddIn oAddin = null;
foreach(ApplicationAddIn item in inventorApplication.ApplicationAddIns) {
if (item.ClassIdString == "{C200B99B-B7DD-4114-A5E9-6557AB5ED8EC}") {
//Trace.TraceInformation("SVF Translator addin is available");
oAddin = (TranslatorAddIn) item;
break;
}
else {}
}
if (oAddin != null) {
//Trace.TraceInformation("SVF Translator addin is available");
TranslationContext oContext = inventorApplication.TransientObjects.CreateTranslationContext();
// Setting context type
oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;
NameValueMap oOptions = inventorApplication.TransientObjects.CreateNameValueMap();
// Create data medium;
DataMedium oData = inventorApplication.TransientObjects.CreateDataMedium();
Trace.TraceInformation("SVF save");
var workingDir = Path.GetDirectoryName(doc.FullFileName);
var sessionDir = Path.Combine(workingDir, "SvfOutput");
// Make sure we delete any old contents that may be in the output directory first,
// this is for local debugging. In DA4I the working directory is always clean
if (Directory.Exists(sessionDir)) {
Directory.Delete(sessionDir, true);
}
oData.FileName = Path.Combine(sessionDir, "result.collaboration");
var outputDir = Path.Combine(sessionDir, "output");
var bubbleFileOriginal = Path.Combine(outputDir, "bubble.json");
var bubbleFileNew = Path.Combine(sessionDir, "bubble.json");
// Setup SVF options
if (oAddin.get_HasSaveCopyAsOptions(doc, oContext, oOptions)) {
oOptions.set_Value("GeometryType", 1);
oOptions.set_Value("EnableExpressTranslation", true);
oOptions.set_Value("SVFFileOutputDir", sessionDir);
oOptions.set_Value("ExportFileProperties", false);
oOptions.set_Value("ObfuscateLabels", true);
}
oAddin.SaveCopyAs(doc, oContext, oOptions, oData);
LogTrace($ "** Saved SVF as {oData.FileName}");
File.Move(bubbleFileOriginal, bubbleFileNew);
viewableOutputDir = sessionDir;
}
}
catch(Exception e) {
LogError($ "********Export to format SVF failed: {e.Message}");
return null;
}
}
return viewableOutputDir;
}
we have met this issue too, this is our setup of SVF output which respects the ground of your design:
oOptions.set_Value("EnableExpressTranslation", false);
oOptions.set_Value("ExportFileProperties", true);
oOptions.set_Value("ObfuscateLabels", false);
For full code you can see our new sample app repository https://github.com/Developer-Autodesk/forge-configurator-inventor/blob/master/AppBundles/CreateSVFPlugin/CreateSvfAutomation.cs#L96

Why is my WinRT app closing when trying to debug my background task?

I am trying to experiment with downloading files on a regular basis with background tasks for windows store applications, and am having trouble.
I followed the sample at https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx, and even downloaded/ran it and everything worked perfectly (including being able to step into the timer background task).
So with that I created my own background task in a brand new Windows namespace
Win8BackgroundTest
{
public class TestBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var uri = new Uri("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov");
var folder = ApplicationData.Current.LocalFolder;
var downloadFile = await folder.CreateFileAsync(uri.Segments.Last(), CreationCollisionOption.GenerateUniqueName);
var dataFile = await folder.CreateFileAsync("downloadData", CreationCollisionOption.GenerateUniqueName);
var downloader = new BackgroundDownloader();
var operation = downloader.CreateDownload(uri, downloadFile);
await FileIO.WriteTextAsync(dataFile, "Success at " + DateTime.Now);
deferral.Complete();
}
public static async void RegisterTask()
{
const string taskName = "TestBackgroundTask";
try
{
var status = await BackgroundExecutionManager.RequestAccessAsync();
if (status == BackgroundAccessStatus.Denied)
{
return;
}
}
catch
{
// already accepted
}
var tasks = BackgroundTaskRegistration.AllTasks
.Where(x => x.Value.Name == taskName)
.ToArray();
if (tasks.Any())
{
return;
}
var builder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = "Win8BackgroundTest.TestBackgroundTask",
};
builder.SetTrigger(new TimeTrigger(60, false));
var registeredTask = builder.Register();
}
}
}
I set up the application's manifest with a Background Tasks declaration, checking the Timer properties checkbox, and set the EntryPoint to Win8BackgroundTest.TestBackgroundTask.
I then added the following at the end of my App.xaml.cs's OnLaunched() method:
TestBackgroundTask.RegisterTask();
Stepping through seems to have task registration work successfully with no exceptions. I then go back to visual studio, added a breakpoint to the first line in my task's Run() method, I then go to the debug locations toolbar, click the down arrow and select TestBackgroundTask. A few seconds later visual studio exits (as does my app).
Does anyone see what I am doing wrong that is causing background tasks to fail?
So after much frustration and a lot of trial and error the issue was a combination of both of the comments.
So first of all, it appears like you cannot have a background task in the same project as the rest of your windows store application. It must be in it's own windows runtime component project.
Finally, there are times where it just doesn't work and for whatever reason deleting the bin and obj folders fix it.

Gdrive unable to download and not upload

I am using GDRive insertFile and RevtrieveAllFiles to upload and download files to googledrive.
I created a client secret and Id and modified the credentials.
the code is based on the post in code project http://www.codeproject.com/KB/WPF/488185/GDrive_Uploader_Sample.zip
but it fails debuggin the Utilities.InsertFile
in the file.upload it fails with exceptionvalue cannot be null - uriString .
in the download it fails in FileList files = request.Fetch(); with
// First, create a reference to the service you wish to use.
// For this app, it will be the Drive service. But it could be Tasks, Calendar, etc.
// The CreateAuthenticator method is passed to the service which will use that when it is time to authenticate
// the calls going to the service.
_service = new DriveService(CreateAuthenticator());
// Open a dialog box for the user to pick a file.
OpenFileDialog dialog = new OpenFileDialog();
dialog.AddExtension = true;
dialog.DefaultExt = ".txt";
dialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Multiselect = false;
dialog.ShowDialog();
File body = new File();
body.Title = System.IO.Path.GetFileName(dialog.FileName);
body.Description = "A test document";
body.MimeType = "text/plain";
System.IO.Stream fileStream = dialog.OpenFile();
byte[] byteArray = new byte[fileStream.Length];
fileStream.Read(byteArray, 0, (int)fileStream.Length);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
// Get a listing of the existing files...
List<File> fileList = Utilities.RetrieveAllFiles(_service);
// Set a flag to keep track of whether the file already exists in the drive
bool fileExists = false;
foreach (File item in fileList)
{
if (item.Title == body.Title)
{
// File exists in the drive already!
fileExists = true;
MessageBoxResult result = System.Windows.MessageBox.Show("The file you picked already exists in your Google Drive. Do you wish to overwrite it?", "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
// Yes... overwrite the file
Utilities.UpdateFile(_service, item.Id, item.Title, item.Description, item.MimeType, dialog.FileName, true);
List<File> allFiles = Utilities.RetrieveAllFiles(_service);
}
else if (result == MessageBoxResult.No)
{
// MessageBoxResult.No code here
File f= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
}
else
{
// MessageBoxResult.Cancel code here
return;
}
break;
}
}
// Check to see if the file existed. If not, it is a new file and must be uploaded.
if (!fileExists)
{
File file= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
var list = Utilities.RetrieveAllFiles(_service);
}
System.Windows.MessageBox.Show("Upload Complete");
open gdrive and set sdk to On. that will enable the application to access the gdrive account

as3 file download restrain?

I have a flash download on my site to download a pdf file.
var myfileReference:FileReference = new FileReference();
down_mc.visible = false;
down_comp.visible = false;
var myRequest:URLRequest = new URLRequest("GEORGIA INCORPORATED.pdf");
myfileReference.addEventListener(IOErrorEvent.IO_ERROR, ioError);
output_txt.text = "";
function ioError(event:ErrorEvent):void {
output_txt.text = "Sorry that there is an IO error during the file downloading. The error is:" + "\n" + event;
}
myfileReference.addEventListener(ProgressEvent.PROGRESS, fileDownloadProgress);
function fileDownloadProgress(event:ProgressEvent):void {
down_mc.visible = true;
}
myfileReference.addEventListener(Event.COMPLETE, fileDownloadCompleted);
function fileDownloadCompleted(evt:Event):void {
down_mc.visible = false;
down_comp.visible = true;
}
function downloadFile (event:MouseEvent):void {
try {
myfileReference.download(myRequest);
} catch (error:SecurityError) {
downloading. The error is:" + "\n" + error;
} catch (error:IllegalOperationError) {
downloading. The error is:" + "\n" + error;
}
}
b1.addEventListener(MouseEvent.CLICK, downloadFile);
the problem is some people want to change the name of the file they are downloading and changing the extension as well, the .pdf , thus making the file unusable. is there any way to restrain the clients from changing the extension?
In pure as3, you cannot force user to save a file under a specific extention. The only way to do it should be to use Air that let you have control on it through a FileStream Object (you can choose file name).
If you want to do it with Air, then you can do :
// Assuming you get your pdf raw data
var pdfData : ByteArray;
var f : File = File.desktopDirectory.resolvePath("myPdf.pdf");
// When user have select a file
f.addEventListener(Event.SELECT, function(e:Event):void{
var targetFile : File = e.target as File;
// Check if the selected file have pdf extension
if(targetFile.nativePath.substr(targetFile.nativePath.length - 4) != ".pdf")
// If not, add it
targetFile = new File(targetFile.nativePath + ".pdf");
// Save the file
var fs : FileStream = new FileStream();
fs.open(targetFile, FileMode.WRITE);
fs.writeBytes(pdfData);
fs.close();
});
// Ask user to save a file (by default on user desktop)
f.browseForSave("Save PDF");