Ejemplo n.º 1
0
        void LoadData(NSMetadataQuery query)
        {
            Console.WriteLine("LoadData()");

            tasks = new List <TaskDocument>();

            foreach (var item in query.Results)
            {
                Console.WriteLine("Found iCloud document for list");

                NSUrl url  = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
                var   task = new TaskDocument(url);
                task.Open((success) => {
                    if (success)
                    {
                        Console.WriteLine("iCloud document added");
                        tasks.Add(task);
                        Reload();                          // hacky to keep doing this...
                    }
                    else
                    {
                        Console.WriteLine("failed to open iCloud document");
                    }
                });
            }
        }
Ejemplo n.º 2
0
        public override void AwakeFromNib()
        {
            // no vertical scrolling, we always want to show all rows
            predicateEditor.EnclosingScrollView.HasVerticalScroller = true;

            previousRowCount = 3;
            predicateEditor.AddRow(this);

            // put the focus in the first text field
            var displayValue = new List <NSObject> (predicateEditor.DisplayValues(1)).Last();

            if (displayValue is NSControl)
            {
                this.Window.MakeFirstResponder((NSResponder)displayValue);
            }

            // create and initalize our query
            query = new NSMetadataQuery();

            // setup our Spotlight notifications
            var nf = NSNotificationCenter.DefaultCenter;

            nf.AddObserver(this, new Selector("queryNotification:"), null, query);

            // initialize our Spotlight query, sort by contact name
            query.SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor("kMDItemContactKeywords", true) };

            // start with our progress search label empty
            progressSearchLabel.StringValue = "";
        }
Ejemplo n.º 3
0
        private Task InstigateDocumentLookupAsync(TaskScheduler synchronizationContextTaskScheduler) =>
        Task.Factory.StartNew(
            () =>
        {
            var query = new NSMetadataQuery
            {
                SearchScopes = new NSObject[]
                {
                    NSMetadataQuery.UbiquitousDocumentsScope
                },
                Predicate = NSPredicate.FromFormat(
                    "%K == %@",
                    new NSObject[]
                {
                    NSMetadataQuery.ItemFSNameKey,
                    new NSString(documentFilename)
                })
            };

            NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification, this.OnQueryFinished, query);
            query.StartQuery();
        },
            CancellationToken.None,
            TaskCreationOptions.None,
            synchronizationContextTaskScheduler);
Ejemplo n.º 4
0
		/// <summary>
		/// Starts a query to look for the sample Test File.
		/// </summary>
		private void FindDocument () {
			Console.WriteLine ("Finding Document...");

			// Create a new query and set it's scope
			Query = new NSMetadataQuery();
			Query.SearchScopes = new NSObject [] {
				NSMetadataQuery.UbiquitousDocumentsScope,
				NSMetadataQuery.UbiquitousDataScope,
				NSMetadataQuery.AccessibleUbiquitousExternalDocumentsScope
			};

			// Build a predicate to locate the file by name and attach it to the query
			var pred = NSPredicate.FromFormat ("%K == %@"
				, new NSObject[] {
				NSMetadataQuery.ItemFSNameKey
				, new NSString(TestFilename)});
			Query.Predicate = pred;

			// Register a notification for when the query returns
			NSNotificationCenter.DefaultCenter.AddObserver (this
				, new Selector("queryDidFinishGathering:")
				, NSMetadataQuery.DidFinishGatheringNotification
				, Query);

			// Start looking for the file
			Query.StartQuery ();
			Console.WriteLine ("Querying: {0}", Query.IsGathering);
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Starts a query to look for the sample Test File.
        /// </summary>
        private void FindDocument()
        {
            Console.WriteLine("Finding Document...");

            // Create a new query and set it's scope
            Query = new NSMetadataQuery();
            Query.SearchScopes = new NSObject [] {
                NSMetadataQuery.UbiquitousDocumentsScope,
                NSMetadataQuery.UbiquitousDataScope,
                NSMetadataQuery.AccessibleUbiquitousExternalDocumentsScope
            };

            // Build a predicate to locate the file by name and attach it to the query
            var pred = NSPredicate.FromFormat("%K == %@"
                                              , new NSObject[] {
                NSMetadataQuery.ItemFSNameKey
                , new NSString(TestFilename)
            });

            Query.Predicate = pred;

            // Register a notification for when the query returns
            NSNotificationCenter.DefaultCenter.AddObserver(this
                                                           , new Selector("queryDidFinishGathering:")
                                                           , NSMetadataQuery.DidFinishGatheringNotification
                                                           , Query);

            // Start looking for the file
            Query.StartQuery();
            Console.WriteLine("Querying: {0}", Query.IsGathering);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads the document.
        /// </summary>
        /// <param name="query">Query.</param>
        private void LoadDocument(NSMetadataQuery query)
        {
            Console.WriteLine("Loading Document...");

            // Take action based on the returned record count
            switch (query.ResultCount)
            {
            case 0:
                // Create a new document
                CreateNewDocument();
                break;

            case 1:
                // Gain access to the url and create a new document from
                // that instance
                NSMetadataItem item = (NSMetadataItem)query.ResultAtIndex(0);
                var            url  = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);

                // Load the document
                OpenDocument(url);
                break;

            default:
                // There has been an issue
                Console.WriteLine("Issue: More than one document found...");
                break;
            }
        }
Ejemplo n.º 7
0
		public override void AwakeFromNib ()
		{
			// no vertical scrolling, we always want to show all rows
			predicateEditor.EnclosingScrollView.HasVerticalScroller = true;
			
			previousRowCount = 3;
			predicateEditor.AddRow (this);
			
			// put the focus in the first text field
			var displayValue = new List<NSObject> (predicateEditor.DisplayValues (1)).Last ();
			if (displayValue is NSControl)
				this.Window.MakeFirstResponder ((NSResponder)displayValue);
			
			// create and initalize our query
			query = new NSMetadataQuery ();
			
			// setup our Spotlight notifications 
			var nf = NSNotificationCenter.DefaultCenter;
			nf.AddObserver (this, new Selector ("queryNotification:"), null, query);
			
			// initialize our Spotlight query, sort by contact name
			query.SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("kMDItemContactKeywords",true) };
			
			// start with our progress search label empty
			progressSearchLabel.StringValue = "";
			 
			
		}
Ejemplo n.º 8
0
        private void LoadDocument(NSMetadataQuery query)
        {
            if (query.ResultCount == 1)
            {
                this.logger.Debug("Query has 1 result.");

                var item = (NSMetadataItem)query.ResultAtIndex(0);
                var url  = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
                var exerciseCloudDocument = new ExerciseCloudDocument(url);

                exerciseCloudDocument.Open(
                    (success) =>
                {
                    if (!success)
                    {
                        this.logger.Error("Failed to open document.");
                        this.exerciseDocument.OnError(new InvalidOperationException("Failed to open document."));
                    }
                    else
                    {
                        this.logger.Info("Loaded document.");
                    }
                });
            }
            else
            {
                var documentsFolder       = Path.Combine(this.ubiquityContainerUrl.Path, "Documents");
                var documentPath          = Path.Combine(documentsFolder, documentFilename);
                var url                   = new NSUrl(documentPath, isDir: false);
                var exerciseCloudDocument = new ExerciseCloudDocument(url)
                {
                    Data = GetDefaultExerciseDocument()
                };

                exerciseCloudDocument.Save(
                    exerciseCloudDocument.FileUrl,
                    UIDocumentSaveOperation.ForCreating,
                    success =>
                {
                    if (success)
                    {
                        this.logger.Info("Successfully created new document.");
                        this.exerciseDocument.OnNext(exerciseCloudDocument.Data);
                    }
                    else
                    {
                        this.logger.Error("Failed to create new document.");
                        this.exerciseDocument.OnError(new InvalidOperationException("Failed to create default document."));
                    }
                });
            }

            // register for document updates
            NSNotificationCenter.DefaultCenter.AddObserver(UIDocument.StateChangedNotification, this.OnDocumentUpdated);
        }
Ejemplo n.º 9
0
        void DidFinishGathering(NSNotification notification)
        {
            Console.WriteLine("DidFinishGathering: notification");
            var query = (NSMetadataQuery)notification.Object;

            query.DisableUpdates();
            query.StopQuery();

            NSNotificationCenter.DefaultCenter.RemoveObserver(this, NSMetadataQuery.DidFinishGatheringNotification, query);
            LoadData(query);
            query = null;
        }
Ejemplo n.º 10
0
        void ScreenCaptureChange(NSNotification notification)
        {
            Console.WriteLine("The " + notification.Name + " message was posted");
            if (notification.Name == "NSMetadataQueryDidUpdateNotification")
            {
                NSMetadataQuery query      = notification.Object as NSMetadataQuery;
                var             latestItem = query != null?query.Results.LastOrDefault() : null;

                if (latestItem != null)
                {
                    ItemDropped(latestItem.Path);
                }
            }
        }
Ejemplo n.º 11
0
        Task BeginQuery()
        {
            if (firstQueryResult != null)
            {
                var t = firstQueryResult;
                firstQueryResult = null;
                if (!t.Task.IsCompleted)
                {
                    t.SetException(new Exception("Stopped"));
                }
            }
            if (query != null)
            {
                query.StopQuery();
            }

            firstQueryResult = new TaskCompletionSource <object> ();

            if (documentsUrl == null)
            {
                firstQueryResult.SetResult(null);
                return(firstQueryResult.Task);
            }

            var queryString = "";
            var head        = "";
            var args        = new List <NSObject> ();

            foreach (var e in FileExtensions)
            {
                queryString += head + "(%K LIKE '*." + e + "')";
                head         = " OR ";
                args.Add(NSMetadataQuery.ItemFSNameKey);
            }

            query = new NSMetadataQuery();
            query.SearchScopes = new NSObject[] { NSMetadataQuery.UbiquitousDocumentsScope };
            query.Predicate    = NSPredicate.FromFormat(
                queryString,
                args.ToArray());

            Console.WriteLine("START iCLOUD QUERY");

            query.StartQuery();

            needsRefresh = false;

            return(firstQueryResult.Task);
        }
Ejemplo n.º 12
0
		void FindDocument () {
			Console.WriteLine ("FindDocument");
			query = new NSMetadataQuery();
			query.SearchScopes = new NSObject [] {NSMetadataQuery.UbiquitousDocumentsScope};
			var pred = NSPredicate.FromFormat ("%K == %@"
								, new NSObject[] {
									NSMetadataQuery.ItemFSNameKey
									, new NSString(monkeyDocFilename)});
			Console.WriteLine ("Predicate:" + pred.PredicateFormat);
			query.Predicate = pred;
			NSNotificationCenter.DefaultCenter.AddObserver (this
				, new Selector("queryDidFinishGathering:")
				, NSMetadataQuery.DidFinishGatheringNotification
				, query);
			
			query.StartQuery ();
		}
Ejemplo n.º 13
0
        public override void DidFinishLaunching(NSNotification notification)
        {
            Console.WriteLine("FinishedLaunching(notification={0})", notification);

            mainWindowController = new MainWindowController();

            InitializeStatusBar();
            //InitializeFirebase();

            _query           = new NSMetadataQuery();
            _query.Predicate = NSPredicate.FromFormat("kMDItemIsScreenCapture = 1");

            NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidStartGatheringNotification, ScreenCaptureChange, _query);
            NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidUpdateNotification, ScreenCaptureChange, _query);
            NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification, ScreenCaptureChange, _query);

            _query.StartQuery();
        }
Ejemplo n.º 14
0
        void StartQuery()
        {
            if (documentMetadataQuery == null)
            {
                documentMetadataQuery = new NSMetadataQuery();
                documentMetadataQuery.SearchScopes = new NSObject[] { NSMetadataQuery.UbiquitousDocumentsScope };

                string todayListName = AppConfig.SharedAppConfiguration.TodayDocumentNameAndExtension;
                documentMetadataQuery.Predicate = NSPredicate.FromFormat("(%K = %@)", NSMetadataQuery.ItemFSNameKey,
                                                                         (NSString)todayListName);

                NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter;
                // TODO: subscribtion https://trello.com/c/1RyX6cJL
                finishGatheringToken = notificationCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification,
                                                                      HandleMetadataQueryUpdates, documentMetadataQuery);
            }

            documentMetadataQuery.StartQuery();
        }
Ejemplo n.º 15
0
        void FindDocument()
        {
            Console.WriteLine("FindDocument");
            query = new NSMetadataQuery();
            query.SearchScopes = new NSObject [] { NSMetadataQuery.UbiquitousDocumentsScope };
            var pred = NSPredicate.FromFormat("%K == %@"
                                              , new NSObject[] {
                NSMetadataQuery.ItemFSNameKey
                , new NSString(monkeyDocFilename)
            });

            Console.WriteLine("Predicate:" + pred.PredicateFormat);
            query.Predicate = pred;
            NSNotificationCenter.DefaultCenter.AddObserver(this
                                                           , new Selector("queryDidFinishGathering:")
                                                           , NSMetadataQuery.DidFinishGatheringNotification
                                                           , query);

            query.StartQuery();
        }
Ejemplo n.º 16
0
        private void LoadFavorites()
        {
            var query = new NSMetadataQuery();

            query.SearchScopes = new NSObject[] { NSMetadataQuery.UbiquitousDocumentsScope };

            var pred =
                NSPredicate.FromFormat(
                    "%K == %@",
                    new NSObject[] {
                NSMetadataQuery.ItemFSNameKey,
                new NSString(FavoritesService.FavoritesFileName)
            });

            query.Predicate = pred;

            NSNotificationCenter.DefaultCenter.AddObserver(
                NSMetadataQuery.DidFinishGatheringNotification,
                OnDidFinishGathering,
                query);

            query.StartQuery();
        }
Ejemplo n.º 17
0
        void LoadTasks(NSNotification notification)
        {
            Console.WriteLine("LoadTasks()");

            if (notification != null && notification.UserInfo != null)
            {
                var u = notification.UserInfo.ValueForKey(new NSString("HasiCloud")) as NSNumber;
                if (u != null)
                {
                    Console.WriteLine("Has iCloud notification:" + u.BoolValue);
                }
            }

            if (AppDelegate.HasiCloud)
            {
                query = new NSMetadataQuery();
                query.SearchScopes = new NSObject [] { NSMetadataQuery.QueryUbiquitousDocumentsScope };
                var pred = NSPredicate.FromFormat("%K like '*.task'"
                                                  , new NSObject[] { NSMetadataQuery.ItemFSNameKey });
                //Console.WriteLine ("Predicate:" + pred.PredicateFormat);
                query.Predicate = pred;
                NSNotificationCenter.DefaultCenter.AddObserver(this
                                                               , new Selector("queryDidFinishGathering:")
                                                               , NSMetadataQuery.DidFinishGatheringNotification
                                                               , query);

                query.StartQuery();
            }
            else
            {
                Console.WriteLine("HasiCloud not populated yet");
                InvokeOnMainThread(() => {
                    var uia = new UIAlertView("Connecting to iCloud...", "Press the \uE049 button to refresh", null, "OK", null);
                    uia.Show();
                });
            }
        }
Ejemplo n.º 18
0
 private void LoadFavoritesDocument(NSMetadataQuery query)
 {
     if (query.ResultCount == 1)
     {
         var item = (NSMetadataItem)query.ResultAtIndex(0);
         var url  = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
         _document = new FavoritesDocument(url);
         _document.Open(success =>
         {
             if (success && _document.Data != null)
             {
                 var favorites = _favoritesService.LoadFavorites();
                 if (favorites.LastUpdated < _document.Data.LastUpdated)
                 {
                     _favoritesService.SaveFavorites(_document.Data);
                 }
             }
         });
     }
     else if (query.ResultCount == 0)
     {
         SaveFavoritesDocument();
     }
 }
        void StartMetadataQuery()
        {
            if (documentMetadataQuery == null)
            {
                NSMetadataQuery metadataQuery = new NSMetadataQuery {
                    SearchScopes = new NSObject[] {
                        NSMetadataQuery.UbiquitousDocumentsScope
                    },
                    Predicate = NSPredicate.FromFormat("(%K.pathExtension = %@)",
                                                       NSMetadataQuery.ItemFSNameKey,
                                                       (NSString)AppConfig.ListerFileExtension)
                };
                documentMetadataQuery = metadataQuery;

                NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter;
                // TODO: use typed overload https://trello.com/c/1RyX6cJL
                finishGatheringToken = notificationCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification,
                                                                      HandleMetadataQueryUpdates, metadataQuery);
                updateToken = notificationCenter.AddObserver(NSMetadataQuery.DidUpdateNotification,
                                                             HandleMetadataQueryUpdates, metadataQuery);
            }

            documentMetadataQuery.StartQuery();
        }
Ejemplo n.º 20
0
		Task BeginQuery ()
		{
			if (firstQueryResult != null) {
				var t = firstQueryResult;
				firstQueryResult = null;
				if (!t.Task.IsCompleted)
					t.SetException (new Exception ("Stopped"));
			}
			if (query != null) {
				query.StopQuery ();
			}

			firstQueryResult = new TaskCompletionSource<object> ();

			if (documentsUrl == null) {
				firstQueryResult.SetResult (null);
				return firstQueryResult.Task;
			}

			var queryString = "";
			var head = "";
			var args = new List<NSObject> ();
			foreach (var e in FileExtensions) {
				queryString += head + "(%K LIKE '*." + e + "')";
				head = " OR ";
				args.Add (NSMetadataQuery.ItemFSNameKey);
			}

			query = new NSMetadataQuery ();
			query.SearchScopes = new NSObject[] { NSMetadataQuery.UbiquitousDocumentsScope };
			query.Predicate = NSPredicate.FromFormat (
				queryString,
				args.ToArray ());

			Console.WriteLine ("START iCLOUD QUERY");

			query.StartQuery ();

			needsRefresh = false;

			return firstQueryResult.Task;
		}
Ejemplo n.º 21
0
 //  Not used in the program was just a test for the Delegate Class
 public NSObject MetadataQueryReplacementValueForAttributevalue(NSMetadataQuery query, string attrName, NSObject attrValue)
 {
     Console.WriteLine("delegate value");
     return(null);
 }
Ejemplo n.º 22
0
 public override void WillTerminate(NSNotification notification)
 {
     _query.StopQuery();
     _query.Delegate = null;
     _query          = null;
 }
Ejemplo n.º 23
0
		void LoadDocument (NSMetadataQuery metadataQuery)
		{
			Console.WriteLine ("LoadDocument");	

			if (metadataQuery.ResultCount == 1) {
				var item = (NSMetadataItem)metadataQuery.ResultAtIndex (0);
				var url = (NSUrl)item.ValueForAttribute (NSMetadataQuery.ItemURLKey);
				doc = new MonkeyDocument (url);
				
				doc.Open (success => {
					if (success) {
						Console.WriteLine ("iCloud document opened");
						Console.WriteLine (" -- {0}", doc.DocumentString);
						viewController.DisplayDocument (doc);
					} else {
						Console.WriteLine ("failed to open iCloud document");
					}
				});

			} else if (metadataQuery.ResultCount == 0) {
				// no document exists, CREATE the first one
				// for a more realistic iCloud application the user will probably 
				// create documents as needed, so this bit of code wouldn't be necessary
				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);
				
				Console.WriteLine ("ubiq:" + ubiq.AbsoluteString);

				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");
					}
				});
			} else {
				Console.WriteLine ("Who put all these other UIDocuments here?");
			}
		}
Ejemplo n.º 24
0
 //  Not used in the program was just a test for the Delegate Class
 public NSObject MetadataQueryReplacementObjectForResultObject(NSMetadataQuery query, NSMetadataItem result)
 {
     Console.WriteLine("delegate object");
     return(null);
 }
Ejemplo n.º 25
0
        void DidFinishGathering(NSNotification notification)
        {
            Console.WriteLine ("DidFinishGathering: notification");
            var query = (NSMetadataQuery)notification.Object;
            query.DisableUpdates();
            query.StopQuery();

            NSNotificationCenter.DefaultCenter.RemoveObserver (this, NSMetadataQuery.DidFinishGatheringNotification, query);
            LoadData(query);
            query = null;
        }
Ejemplo n.º 26
0
        void LoadData(NSMetadataQuery query)
        {
            Console.WriteLine ("LoadData()");

            tasks = new List<TaskDocument>();

            foreach (var item in query.Results) {
                Console.WriteLine ("Found iCloud document for list");

                NSUrl url = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
                var task = new TaskDocument(url);
                task.Open ( (success) => {
                    if (success) {
                        Console.WriteLine ("iCloud document added");
                        tasks.Add (task);
                        Reload (); // hacky to keep doing this...
                    } else
                        Console.WriteLine ("failed to open iCloud document");
                });
            }
        }
		void StartQuery()
		{
			if (documentMetadataQuery == null) {
				documentMetadataQuery = new NSMetadataQuery ();
				documentMetadataQuery.SearchScopes = new NSObject[]{ NSMetadataQuery.UbiquitousDocumentsScope };

				string todayListName = AppConfig.SharedAppConfiguration.TodayDocumentNameAndExtension;
				documentMetadataQuery.Predicate = NSPredicate.FromFormat ("(%K = %@)", NSMetadataQuery.ItemFSNameKey,
					(NSString)todayListName);

				NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter;
				// TODO: subscribtion https://trello.com/c/1RyX6cJL
				finishGatheringToken = notificationCenter.AddObserver (NSMetadataQuery.DidFinishGatheringNotification,
					HandleMetadataQueryUpdates, documentMetadataQuery);
			}

			documentMetadataQuery.StartQuery ();
		}
Ejemplo n.º 28
0
        void LoadTasks(NSNotification notification)
        {
            Console.WriteLine ("LoadTasks()");

            if (notification != null && notification.UserInfo != null) {
                var u = notification.UserInfo.ValueForKey(new NSString("HasiCloud")) as NSNumber;
                if (u != null)
                    Console.WriteLine ("Has iCloud notification:"+ u.BoolValue);
            }

            if (AppDelegate.HasiCloud) {
                query = new NSMetadataQuery();
                query.SearchScopes = new NSObject [] {NSMetadataQuery.QueryUbiquitousDocumentsScope};
                var pred = NSPredicate.FromFormat ("%K like '*.task'"
                            , new NSObject[] {NSMetadataQuery.ItemFSNameKey});
                //Console.WriteLine ("Predicate:" + pred.PredicateFormat);
                query.Predicate = pred;
                NSNotificationCenter.DefaultCenter.AddObserver (this
                    , new Selector("queryDidFinishGathering:")
                    ,NSMetadataQuery.DidFinishGatheringNotification
                    , query);

                query.StartQuery ();
            } else {
                Console.WriteLine ("HasiCloud not populated yet");
                InvokeOnMainThread(()=>{
                 	var uia = new UIAlertView("Connecting to iCloud...", "Press the \uE049 button to refresh",null, "OK", null);
                    uia.Show ();
                });
            }
        }
Ejemplo n.º 29
0
		/// <summary>
		/// Loads the document.
		/// </summary>
		/// <param name="query">Query.</param>
		private void LoadDocument (NSMetadataQuery query) {
			Console.WriteLine ("Loading Document...");	

			// Take action based on the returned record count
			switch (query.ResultCount) {
			case 0:
				// Create a new document
				CreateNewDocument ();
				break;
			case 1:
				// Gain access to the url and create a new document from
				// that instance
				NSMetadataItem item = (NSMetadataItem)query.ResultAtIndex (0);
				var url = (NSUrl)item.ValueForAttribute (NSMetadataQuery.ItemURLKey);

				// Load the document
				OpenDocument (url);
				break;
			default:
				// There has been an issue
				Console.WriteLine ("Issue: More than one document found...");
				break;
			}
		}
Ejemplo n.º 30
0
        void LoadDocument(NSMetadataQuery query)
        {
            Console.WriteLine("LoadDocument");

            if (query.ResultCount == 1)
            {
                NSMetadataItem item = (NSMetadataItem)query.ResultAtIndex(0);
                var            url  = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
                doc = new MonkeyDocument(url);

                doc.Open((success) => {
                    if (success)
                    {
                        Console.WriteLine("iCloud document opened");
                        Console.WriteLine(" -- " + doc.DocumentString);
                        viewController.DisplayDocument(doc);
                    }
                    else
                    {
                        Console.WriteLine("failed to open iCloud document");
                    }
                });
            }
            else if (query.ResultCount == 0)
            {
                // no document exists, CREATE the first one
                // for a more realistic iCloud application the user will probably
                // create documents as needed, so this bit of code wouldn't be necessary
                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);

                Console.WriteLine("ubiq:" + ubiq.AbsoluteString);

                var doc = new MonkeyDocument(ubiq);

                doc.Save(doc.FileUrl, UIDocumentSaveOperation.ForCreating
                         , (saveSuccess) => {
                    Console.WriteLine("Save completion:" + saveSuccess);
                    if (saveSuccess)
                    {
                        doc.Open((openSuccess) => {
                            Console.WriteLine("Open completion:" + openSuccess);
                            if (openSuccess)
                            {
                                Console.WriteLine("new document for iCloud");
                                Console.WriteLine(" == " + doc.DocumentString);
                                viewController.DisplayDocument(doc);
                            }
                            else
                            {
                                Console.WriteLine("couldn't open");
                            }
                        });
                    }
                    else
                    {
                        Console.WriteLine("couldn't save");
                    }
                });
            }
            else
            {
                Console.WriteLine("Who put all these other UIDocuments here?");
            }
        }
Ejemplo n.º 31
0
		//  Not used in the program was just a test for the Delegate Class
		public NSObject MetadataQueryReplacementValueForAttributevalue (NSMetadataQuery query, string attrName, NSObject attrValue)
		{
			Console.WriteLine ("delegate value");
			return null;
		}
Ejemplo n.º 32
0
		//  Not used in the program was just a test for the Delegate Class
		public NSObject MetadataQueryReplacementObjectForResultObject (NSMetadataQuery query, NSMetadataItem result)
		{
			Console.WriteLine ("delegate object");
			return null;
		}
        private Task InstigateDocumentLookupAsync(TaskScheduler synchronizationContextTaskScheduler) =>
            Task.Factory.StartNew(
                () =>
                {
                    var query = new NSMetadataQuery
                    {
                        SearchScopes = new NSObject[]
                        {
                            NSMetadataQuery.UbiquitousDocumentsScope
                        },
                        Predicate = NSPredicate.FromFormat(
                            "%K == %@",
                            new NSObject[]
                            {
                                NSMetadataQuery.ItemFSNameKey,
                                new NSString(documentFilename)
                            })
                    };

                    NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification, this.OnQueryFinished, query);
                    query.StartQuery();
                },
                CancellationToken.None,
                TaskCreationOptions.None,
                synchronizationContextTaskScheduler);
        private void LoadDocument(NSMetadataQuery query)
        {
            if (query.ResultCount == 1)
            {
                this.logger.Debug("Query has 1 result.");

                var item = (NSMetadataItem)query.ResultAtIndex(0);
                var url = (NSUrl)item.ValueForAttribute(NSMetadataQuery.ItemURLKey);
                var exerciseCloudDocument = new ExerciseCloudDocument(url);

                exerciseCloudDocument.Open(
                    (success) =>
                    {
                        if (!success)
                        {
                            this.logger.Error("Failed to open document.");
                            this.exerciseDocument.OnError(new InvalidOperationException("Failed to open document."));
                        }
                        else
                        {
                            this.logger.Info("Loaded document.");
                        }
                    });
            }
            else
            {
                var documentsFolder = Path.Combine(this.ubiquityContainerUrl.Path, "Documents");
                var documentPath = Path.Combine(documentsFolder, documentFilename);
                var url = new NSUrl(documentPath, isDir: false);
                var exerciseCloudDocument = new ExerciseCloudDocument(url)
                {
                    Data = GetDefaultExerciseDocument()
                };

                exerciseCloudDocument.Save(
                    exerciseCloudDocument.FileUrl,
                    UIDocumentSaveOperation.ForCreating,
                    success =>
                    {
                        if (success)
                        {
                            this.logger.Info("Successfully created new document.");
                            this.exerciseDocument.OnNext(exerciseCloudDocument.Data);
                        }
                        else
                        {
                            this.logger.Error("Failed to create new document.");
                            this.exerciseDocument.OnError(new InvalidOperationException("Failed to create default document."));
                        }
                    });
            }

            // register for document updates
            NSNotificationCenter.DefaultCenter.AddObserver(UIDocument.StateChangedNotification, this.OnDocumentUpdated);
        }
		void StartMetadataQuery()
		{
			if (documentMetadataQuery == null) {
				NSMetadataQuery metadataQuery = new NSMetadataQuery {
					SearchScopes = new NSObject[] {
						NSMetadataQuery.UbiquitousDocumentsScope
					},
					Predicate = NSPredicate.FromFormat ("(%K.pathExtension = %@)",
						NSMetadataQuery.ItemFSNameKey,
						(NSString)AppConfig.ListerFileExtension)
				};
				documentMetadataQuery = metadataQuery;

				NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter;
				// TODO: use typed overload https://trello.com/c/1RyX6cJL
				finishGatheringToken = notificationCenter.AddObserver (NSMetadataQuery.DidFinishGatheringNotification,
					HandleMetadataQueryUpdates, metadataQuery);
				updateToken = notificationCenter.AddObserver (NSMetadataQuery.DidUpdateNotification,
					HandleMetadataQueryUpdates, metadataQuery);
			}

			documentMetadataQuery.StartQuery ();
		}