Xamarin ios Cloud file copy location issue - ios

I had connected iCloud using xamarin forms ios. My file copied to icloud without any error. But it saved in file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~companyname~MobileDoc/ path.
When i checked inside iCloud my file not showing it. But when i search that file, its location shows as iCloud --> MobileDoc--> File.txt. But when i checked inside the iCloud there are no Folder call MobileDoc.
This is the example i tried Here
This is the code i am using to save the document.
var uburl = NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null);
if (uburl == null)
{
HasiCloud = false;
}
else
{
HasiCloud = true;
iCloudUrl = uburl;
var docsFolder = Path.Combine(iCloudUrl.Path, "Documents");
var filePath = Path.Combine(docsFolder, fileName);
FileService.Save(filePath, attachment.Content);
if (option == false)
FileService.Instance.Open(filePath);
}

Saving iCloud Documents
To add a UIDocument to iCloud you can call UIDocument.Save directly (for new documents only) or move an existing file using NSFileManager.DefaultManager.SetUbiquitious. The example code creates a new document directly in the ubiquity container with this code (there are two completion handlers here, one for the Save operation and another for the Open):
var docsFolder = Path.Combine (iCloudUrl.Path, "Documents"); // NOTE: Documents folder is user-accessible in Settings
var docPath = Path.Combine (docsFolder, MonkeyDocFilename);
var ubiq = new NSUrl (docPath, false);
var monkeyDoc = new MonkeyDocument (ubiq);
monkeyDoc.Save (monkeyDoc.FileUrl, UIDocumentSaveOperation.ForCreating, saveSuccess => {
Console.WriteLine ("Save completion:" + saveSuccess);
if (saveSuccess) {
monkeyDoc.Open (openSuccess => {
Console.WriteLine ("Open completion:" + openSuccess);
if (openSuccess) {
Console.WriteLine ("new document for iCloud");
Console.WriteLine (" == " + monkeyDoc.DocumentString);
viewController.DisplayDocument (monkeyDoc);
} else {
Console.WriteLine ("couldn't open");
}
});
} else {
Console.WriteLine ("couldn't save");
}
According to document ,when you save file to icloud,you need to use UIDocument .This will be Safe and stable.

Related

How to add files to a list in vala?

I want to add files to a list and then access them in a for loop. This is how I try to do it:
private get_app_list () {
var file = new File.new_for_path (/usr/share/applications);
List<File> app_list = new List<File> ();
foreach (File desktop_file in app_list) {
// other code here
}
}
What is the right way to access files stored in a directory and then add them to a list??
using Posix;
...
List<File> app_list = new List<File> ();
//Open directory. Returns null on error
var dirHandle = Posix.opendir("/usr/share/applications");
unowned DirEnt entry;
//While there is an entry to read in the directory
while((entry = readdir(dir)) != null) {
//Get the name
var name = (string) entry.d_name;
//And add a new file to the app_list
app_list.add(new File.new_for_path("/usr/share/applications"+name);
}
If you want to merely display the available apps on system, you could use the utilities supplied by the Gio-2.0 lib. After adding dependency ('gio-2.0'), to your meson.build file you could use code similar to the following:
/* We use a `GListStore` here, which is a simple array-like list implementation
* for manual management.
* List models need to know what type of data they provide, so we need to
* provide the type here. As we want to do a list of applications, `GAppInfo`
* is the object we provide.
*/
var app_list = new GLib.ListStore (typeof (GLib.AppInfo));
var apps = GLib.AppInfo.get_all ();
foreach (var app in apps) {
app_list.append (app);
}
If however you need to list files inside a directory, it's possible also to use the higher level API provided by the same gio-2.0 library. Here is a sample code to enumerate files inside "/usr/share/applications/"
void main () {
var app_dir = GLib.File.new_for_path ("/usr/share/applications");
try {
var cancellable = new Cancellable ();
GLib.FileEnumerator enumerator = app_dir.enumerate_children (
GLib.FileAttribute.STANDARD_DISPLAY_NAME,
GLib.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
cancellable
);
FileInfo ? file_info = null;
while (!cancellable.is_cancelled () &&
((file_info = enumerator.next_file (cancellable)) != null)) {
// Ignore directories
if (file_info.get_file_type () == GLib.FileType.DIRECTORY) {
continue;
}
// files could be added to a list_store here.
/*
* var files_list = new GLib.ListStore (typeof (GLib.FileInfo));
* files_list.append (file_info);
*/
print (file_info.get_display_name () + "\n");
}
} catch (GLib.Error err) {
info ("%s\n", err.message);
}
}
I hope this could be of any help.

Xamarin - IOS - Video assets in Photo library - Find By name

I'm new in Xamarin development.
I build my app, where user can clicks on DOWNLOAD button.
This button download video from the server and save to Photo library.
Here is how I implement this (maybe its incorrect way??)
public bool SaveVideo(byte[] videoData, int id)
{
try
{
CreateCustomAlbum();
// Save file to applicaiton folder
string local_path = SaveFileToApplicationFolder(videoData);
_lib.WriteVideoToSavedPhotosAlbum(new Foundation.NSUrl(local_path), (t, u) =>
{
DeleteLocalFile(local_path); // HERE I DELETE FILE FOR NOT INCREASE SIZE OF APPLICATION
_local_file_path = t.AbsoluteUrl.ToString(); // global variable
_lib.Enumerate(ALAssetsGroupType.Album, HandleALAssetsLibraryGroupsEnumerationResultsDelegate, (obj) => { });
});
return true;
}
catch (Exception ex)
{
return false;
}
}
void DeleteLocalFile(string local_path)
{
try
{
if (File.Exists(local_path))
{
File.Delete(local_path);
if (!File.Exists(local_path))
{
Console.WriteLine("Deleted");
}
}
}
catch (Exception ex)
{
}
}
string SaveFileToApplicationFolder(byte[] videoData)
{
try
{
string file_path = String.Empty;
var doc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filename = "MY-APP-" + id + ".mp4"; // id global variable
file_path = Path.Combine(doc, filename); // global variable
File.WriteAllBytes(file_path, videoData);
return file_path;
}
catch (Exception ex)
{
return String.Empty;
}
}
void HandleALAssetsLibraryGroupsEnumerationResultsDelegate(ALAssetsGroup group, ref bool stop)
{
try
{
if (group == null)
{
stop = true;
return;
}
if (group.Name == "MY-APP-ALBUM-NAME")
{
stop = true;
_current_album = group;
SaveFileToCustomAlbum();
}
}
catch (Exception ex)
{
}
}
void SaveFileToCustomAlbum()
{
try
{
if (_current_album != null && !String.IsNullOrEmpty(_local_file_path))
{
_lib.AssetForUrl(new Foundation.NSUrl(_local_file_path), delegate (ALAsset asset)
{
if (asset != null)
{
_current_album.AddAsset(asset);
}
else
{
Console.WriteLine("ASSET == NULL.");
}
}, delegate (NSError assetError)
{
Console.WriteLine(assetError.ToString());
});
}
}
catch (Exception ex)
{
}
}
So this code do:
1) Save video to local folder my video - Method SaveFileToApplicationFolder
2) Then Save video file to Photo library - Method SaveVideo
3) Then Delete file from app folder (in purpose not increase application folder size (app size) --- IF ITS CORRECT logic??
4) Then put assets to Custom Album for my App
SO everything here works well for me......BUT!
I need overtime when user open item - check if he already has video for this item in photos library or not?
And here I'm stack....i just don't understand how i can to check if user has specific video?? I don't find hot to set NAME for ASSETS and hot looking for assets by name...so don't know hot to find this assets....METADATA?? Key_VALUE of object??
Refer to Obj-C Check if image already exists in Photos gallery
In short:
Store assetUrl when saving video with NSUserDefaults
Check if the video exists in Photo library with assetUrl when next time to open it .
You may just want to use xam.plugin.media nuget package. It makes it very easy to take and store videos as well as access the default video picker for selecting existing videos

Creating a hyperlink in active cell from uploaded file

I'm designing a shared Google Sheets for our team to keep track of each piece of content we produce. I want to implement a feature that allows people to upload a preview clip and have a hyperlink automatically created within the active cell.
My script so far serves up HTML as a user interface with a file upload and name entry. This part works fine and allows anyone to upload straight to Google Drive.
I've been having trouble getting it to automatically create a hyperlink in the active cell to the uploaded file. Been searching around, but haven't had a great deal of luck.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('File Upload')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Upload A File');
}
function uploadFiles(form) {
try {
var dropbox = "Clips";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
My suggestion is to modify the return value from uploadFiles() to be an object, then use the URL to populate a spreadsheet HYPERLINK() formula.
return "File uploaded successfully " + file.getUrl();
Becomes:
return {
result: "File uploaded successfully",
fileURL: file.getUrl(),
fileDesc: file.getDescription() // Could be other values
};
Next, a function that sets the formula. This server-side function would be called with the values to be used in the formula, which were previously returned from uploadFiles(). I'm assuming this is from your client-side JavaScript, but that's just a guess, since you didn't include that in your question.
function setHyperlink( fileURL, fileDesc ) {
var formula = '=HYPERLINK("' + fileURL + '","' + fileDesc + '")';
SpreadsheetApp.getActiveCell()
.setFormula( formula );
return true;
}
I ended up solving this issue using the GAS Properties Service - creating 2 new User Properties to contain URL and Name data.
I also found a few issues with getActiveCell - it kept placing the link in A1. Although I had used Google's suggested method for returning the active cell, I was able to use the fix suggested here:
http://bit.ly/20Gc7l6
Here's my final script
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('File Upload')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Upload A File');
}
function uploadFiles(form) {
try {
var dropbox = "Blacksand Clips";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription(file.getDescription());
var userProperties = PropertiesService.getUserProperties();
var link = file.getUrl();
var name = file.getName();
userProperties.setProperty('link', link);
userProperties.setProperty('name', name);
setHyperlink();
return "File uploaded successfully ";
} catch (error) {
return error.toString();
}
}
function setHyperlink() {
var userProperties = PropertiesService.getUserProperties();
var link = userProperties.getProperty('link');
var displayName = userProperties.getProperty('name');
var value = 'hyperlink("' + link + '","' + displayName + '")'
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell().activate();
cell.setFormula( value )
return true;
}

Use OS.File to test if path is locked?

With OS.File I am able to open a file with lock on it:
let options = {
winShare: 0 // Exclusive lock on Windows
};
if (OS.Constants.libc.O_EXLOCK) {
// Exclusive lock on *nix
options.unixFlags = OS.Constants.libc.O_EXLOCK;
}
let file = yield OS.File.open(..., options);
Is it possible to test if the path is locked though. I'm looking for alternative to nsiToolkitProfile.lockProfile
This is copy paste to scratchpad code. The top block uses nsitoolkitprofile to test if locked. And it works fine. The second part uses OS.File.open and it always throws error.
Cu.import('resource://gre/modules/osfile.jsm');
Cu.import('resource://gre/modules/FileUtils.jsm');
var tps = Cc['#mozilla.org/toolkit/profile-service;1'].createInstance(Ci.nsIToolkitProfileService); //toolkitProfileService
var folderOfProfile = 'k46wtieb.clean'; //folder names of relative profiles found here: %APPDATA%\Mozilla\Firefox\Profiles
var rootPathDefault = FileUtils.getFile('DefProfRt', []).path;
var localPathDefault = FileUtils.getFile('DefProfLRt', []).path;
var aDirect = new FileUtils.File(OS.Path.join(rootPathDefault, folderOfProfile));
var aTemp = new FileUtils.File(OS.Path.join(localPathDefault, folderOfProfile));
try {
var locker = tps.lockProfilePath(aDirect, aTemp)
Services.ww.activeWindow.alert('NOT open');
locker.unlock();
} catch (ex) {
if (ex.result == Cr.NS_ERROR_FILE_ACCESS_DENIED) {
Services.ww.activeWindow.alert('its in use');
} else {
throw ex;
}
}
var promise = OS.File.open(aDirect.path)
promise.then(
function(aVal) {
Services.ww.activeWindow.alert('promise success, aVal = ' + aVal);
aVal.close();
},
function(aReason) {
Services.ww.activeWindow.alert('promise rejected, aReason = ' + uneval(aReason));
}
)
The promise is always rejected with aReason.becauseAccessDenied every time :(
Just try to open it... If you cannot because of permissions, then the file is probably locked in another location.

How to open the page in browser at the time of uninstalling the firefox addon

I want to open the link when the user uninstalls the addon, so for this what i have to code and under which event.
If anybody know about this then please help me out.
Currently this is what I am doing at the time of uninstall. But gBrowser.addTab(Website + 'uninstalled=true&token=' + uniqueguid); is not working over here.
var UninstallObserver = {
_uninstall : false,
observe : function(subject, topic, data) {
//===Write Code here for Delete File Uninsatll Time
//alert("Uninstall Time Delete File");
var Filename = "webmail";
// Delete all template file.
try{
var pref = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var finished = "";
pref.setBoolPref("myextension.install.just_installed", false);
}
catch(e) {}
gBrowser.addTab(Website + 'uninstalled=true&token=' + uniqueguid);
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path+"\\DefaultTemplate.txt");
if ( file.exists() == true )
{
var aFile = Components.classes["#mozilla.org/file/local;1"].createInstance();
if (aFile instanceof Components.interfaces.nsILocalFile)
{
aFile.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path + "\\DefaultTemplate.txt");
aFile.remove(false);
}
}
//=======
if (topic == "em-action-requested") {
subject.QueryInterface(Components.interfaces.nsIUpdateItem);
if (subject.id == MY_EXTENSION_UUID)
{
if (data == "item-uninstalled")
{
//==Delete File Whenever Uninstall
//alert("When Uninatall");
//===========
data = "item-cancel-action";
this._uninstall = true;
}
if (data == "disabled")
{
// alert("You are not allow to disable SysLocker.");
this._uninstall = true;
}
else if (data == "item-cancel-action")
{
this._uninstall = false;
}
}
}
else if (topic == "quit-application-granted")
{
data = "item-cancel-action";
if (this._uninstall)
{
//Code here to delete registry
}
this.unregister();
}
},
register : function() {
var observerService =
Components.classes["#mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "em-action-requested", false);
observerService.addObserver(this, "quit-application-granted", false);
},
unregister : function() {
var observerService =
Components.classes["#mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this,"em-action-requested");
observerService.removeObserver(this,"quit-application-granted");
}
}
Thanks
0) What kind of extension is this? I assume it's a regular extension requiring restart; bootstrapped (restartless) extensions have their own uninstall notification.
1) Per the MDC docs, the em-action-requested notification was replaced with a different notification in Firefox 4+, are you testing with Firefox 4 or 3.6?
2) How exactly is gBrowser.addTab "not working over here"? Does the code get to that point? Do you get any messages in the Error Console (see that page for set up tips)? If you put your code in an XPCOM component (which is correct), you'll first have to get a reference to a browser window. See Working with windows in chrome code.
I don't think that the em-action-requested topic is posted to observers until the extension is actually uninstalled, which happens on restart (assuming it is not a restartless extension). When are you expecting the new tab to appear? I would try setting a pref when the uninstall topic is triggered and checking for that pref on startup. If it is there, you can display your tab and remove the pref.

Resources