CKQueryOperation CreateLoadBatchOperation() { CKQueryOperation queryOp = null; if (postCursor != null) { // If we have a cursor, go ahead and just continue from where we left off queryOp = new CKQueryOperation(postCursor); } else { CKQuery postQuery = CreatePostQuery(); queryOp = new CKQueryOperation(postQuery); } downloadingBatchStorage.Clear(); // This query should only fetch so many records and only retrieve the information we need queryOp.ResultsLimit = updateBy; queryOp.DesiredKeys = desiredKeys; queryOp.RecordFetched = OnPostFetched; queryOp.Completed = OnPostLoadingCompleted; queryOp.Database = PublicDB; return(queryOp); }
public void QueryForRecords (CLLocation location, Action<List<CKRecord>> completionHandler) { var radiusInKilometers = NSNumber.FromFloat (5f); var predicate = NSPredicate.FromFormat ("distanceToLocation:fromLocation:(location, %@) < %f", new NSObject[] { location, radiusInKilometers }); var query = new CKQuery (ItemRecordType, predicate) { SortDescriptors = new [] { new NSSortDescriptor ("creationDate", false) } }; var queryOperation = new CKQueryOperation (query) { DesiredKeys = new [] { NameField } }; var results = new List<CKRecord> (); queryOperation.RecordFetched = (record) => results.Add (record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine ("An error occured: {0}", error.Description); return; } DispatchQueue.MainQueue.DispatchAsync (() => completionHandler (results)); }; publicDatabase.AddOperation (queryOperation); }
public void QueryForRecords(string referenceRecordName, Action <List <CKRecord> > completionHandler) { var recordId = new CKRecordID(referenceRecordName); var parent = new CKReference(recordId, CKReferenceAction.None); var predicate = NSPredicate.FromFormat("parent == %@", parent); var query = new CKQuery(ReferenceSubItemsRecordType, predicate) { SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) } }; var queryOperation = new CKQueryOperation(query) { DesiredKeys = new [] { NameField } }; var results = new List <CKRecord> (); queryOperation.RecordFetched = (record) => results.Add(record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine("An error occured: {0}", error.Description); return; } DispatchQueue.MainQueue.DispatchAsync(() => completionHandler(results)); }; publicDatabase.AddOperation(queryOperation); }
public void QueryForRecords(CLLocation location, Action <List <CKRecord> > completionHandler) { var radiusInKilometers = NSNumber.FromFloat(5f); var predicate = NSPredicate.FromFormat("distanceToLocation:fromLocation:(location, %@) < %f", new NSObject[] { location, radiusInKilometers }); var query = new CKQuery(ItemRecordType, predicate) { SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) } }; var queryOperation = new CKQueryOperation(query) { DesiredKeys = new [] { NameField } }; var results = new List <CKRecord> (); queryOperation.RecordFetched = (record) => results.Add(record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine("An error occured: {0}", error.Description); return; } DispatchQueue.MainQueue.DispatchAsync(() => completionHandler(results)); }; publicDatabase.AddOperation(queryOperation); }
private void RunQuery() { // The objective-c version takes a format string and a variadic argument // list for substititon, but we only support sending an unformatted string // down. Marshalling variadic arguments is tricky.... // Just do your formatting on the C# side. // Note that passing a bad predicate string will throw an exception // Pick a random name out of the hat var queryStr = string.Format("name = '{0}'", names[UnityEngine.Random.Range(0, names.Length)]); Debug.Log(string.Format("Running query with predicate ({0})", queryStr)); // Queries are made with NSPredicate which sorta like SQL and sorta // like regular expressions. // See https://nshipster.com/nspredicate/ for a quick intro to the kinds // of queries you can run. Were just going to do a simple key,value search CKQuery query = new CKQuery("Person", NSPredicate.PredicateWithFormat(queryStr)); // The second argument here is the container to search in. Unless you // are using custom containers, you'll want to pass null for the // default container database.PerformQuery(query, null, OnQueryComplete); }
public void FetchRecords(string recordType, Action <List <CKRecord> > completionHandler) { var truePredicate = NSPredicate.FromValue(true); var query = new CKQuery(recordType, truePredicate) { SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) } }; var queryOperation = new CKQueryOperation(query) { DesiredKeys = new [] { NameField } }; var results = new List <CKRecord> (); queryOperation.RecordFetched = (record) => results.Add(record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine("An error occured: {0}", error.Description); return; } InvokeOnMainThread(() => completionHandler(results)); }; publicDatabase.AddOperation(queryOperation); }
public void SetUp() { TestRuntime.AssertXcodeVersion(6, 0); TestRuntime.AssertSystemVersion(ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false); q = new CKQuery("Foo", NSPredicate.FromFormat("email = '@xamarin'")); op = new CKQueryOperation(q); }
public async override Task<Results> Run () { var location = Location; if (location == null) return null; var container = CKContainer.DefaultContainer; var publicDB = container.PublicCloudDatabase; var query = new CKQuery ("Items", NSPredicate.FromValue (true)) { SortDescriptors = new NSSortDescriptor [] { new CKLocationSortDescriptor ("location", location) } }; var defaultZoneId = new CKRecordZoneID (CKRecordZone.DefaultName, CKContainer.OwnerDefaultName); CKRecord [] recordArray = await publicDB.PerformQueryAsync (query, defaultZoneId); var results = new Results (alwaysShowAsList: true); var len = recordArray.Length; if(len == 0) ListHeading = "No matching items"; else if (len == 1) ListHeading = "Found 1 matching item:"; else ListHeading = $"Found {recordArray.Length} matching items:"; results.Items.AddRange (recordArray.Select (r => new CKRecordWrapper (r))); return results; }
public void FetchRecords (string recordType, Action<List<CKRecord>> completionHandler) { var truePredicate = NSPredicate.FromValue (true); var query = new CKQuery (recordType, truePredicate) { SortDescriptors = new [] { new NSSortDescriptor ("creationDate", false) } }; var queryOperation = new CKQueryOperation (query) { DesiredKeys = new [] { ValueField } }; var results = new List<CKRecord> (); queryOperation.RecordFetched = (record) => { results.Add (record); }; queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine ("An error occured: {0}", error.Description); return; } InvokeOnMainThread (() => completionHandler (results)); }; privateDatabase.AddOperation (queryOperation); }
public void Can_create_CKQuery() { var recordType = "record_type"; var predicate = NSPredicate.PredicateWithValue(false); var query = new CKQuery(recordType, predicate); Assert.AreEqual(query.RecordType, recordType); Assert.AreEqual(query.Predicate, predicate); }
CKQuery CreateLoadNewPostQuery() { // Creates predicate based on tag string and most recent post from server NSPredicate predicate = CreateLoadNewPostPredicate(); var postQuery = new CKQuery(Post.RecordType, predicate); postQuery.SortDescriptors = Utils.CreateCreationDateDescriptor(ascending: true); return(postQuery); }
public static async Task <int> GetPastPurchasesAsync() { var container = CKContainer.DefaultContainer; var status = await container.GetAccountStatusAsync(); var hasCloud = status == CKAccountStatus.Available; if (!hasCloud) { return(0); } var db = container.PrivateCloudDatabase; var pred = NSPredicate.FromFormat("TransactionId != 'tttt'"); var query = new CKQuery("PatronSubscription", pred); var recs = await db.PerformQueryAsync(query, CKRecordZone.DefaultRecordZone().ZoneId); Console.WriteLine("NUM PATRON RECS = {0}", recs.Length); var subs = recs.Select(x => new PatronSubscription(x)).OrderBy(x => x.PurchaseDate).ToArray(); var ed = DateTime.UtcNow; if (subs.Length > 0) { ed = subs[0].PurchaseEndDate; foreach (var s in subs.Skip(1)) { if (s.PurchaseDate < ed) { ed = ed.AddMonths(s.NumMonths); } else { ed = s.PurchaseEndDate; } } } Console.WriteLine("NEW END DATE = {0}", ed); var endDate = ed; var isPatron = DateTime.UtcNow < endDate; var settings = DocumentAppDelegate.Shared.Settings; settings.IsPatron = isPatron; settings.PatronEndDate = endDate; return(subs.Length); }
public void Cant_create_CKQuery_with_invalid_record_type( [Values(null, "")] string recordType ) { TestDelegate sut = () => { var predicate = NSPredicate.PredicateWithValue(false); var query = new CKQuery(recordType, predicate); }; Assert.Throws <CloudKitException>(sut); }
void DoSomethingBad() { try { var pred = NSPredicate.PredicateWithFormat(""); var queyr = new CKQuery("SomeType", pred); } catch (CloudKitException ex) { Debug.Log("Well i tried my best"); Debug.LogError(ex); } }
public IEnumerator Can_run_query() { var database = CKContainer.DefaultContainer().PrivateCloudDatabase; var query = new CKQuery("mytype", NSPredicate.PredicateWithValue(true)); var wasCalled = false; var zoneId = new CKRecordZoneID("zoneid", "me"); database.PerformQuery(query, zoneId, (records, error) => { wasCalled = true; }); yield return(WaitUntilWithTimeout(() => wasCalled, DefaultTimeout)); Assert.IsTrue(wasCalled); }
public static async Task<int> GetPastPurchasesAsync () { var container = CKContainer.DefaultContainer; var status = await container.GetAccountStatusAsync (); var hasCloud = status == CKAccountStatus.Available; if (!hasCloud) return 0; var db = container.PrivateCloudDatabase; var pred = NSPredicate.FromFormat ("TransactionId != 'tttt'"); var query = new CKQuery ("PatronSubscription", pred); var recs = await db.PerformQueryAsync (query, CKRecordZone.DefaultRecordZone().ZoneId); Console.WriteLine ("NUM PATRON RECS = {0}", recs.Length); var subs = recs.Select (x => new PatronSubscription (x)).OrderBy (x => x.PurchaseDate).ToArray (); var ed = DateTime.UtcNow; if (subs.Length > 0) { ed = subs[0].PurchaseEndDate; foreach (var s in subs.Skip (1)) { if (s.PurchaseDate < ed) { ed = ed.AddMonths (s.NumMonths); } else { ed = s.PurchaseEndDate; } } } Console.WriteLine ("NEW END DATE = {0}", ed); var endDate = ed; var isPatron = DateTime.UtcNow < endDate; var settings = DocumentAppDelegate.Shared.Settings; settings.IsPatron = isPatron; settings.PatronEndDate = endDate; return subs.Length; }
private IEnumerator RunQueryCo() { Debug.Log("waiting 5 seconds before running query..."); yield return(new WaitForSeconds(5f)); Debug.Log("fetching sorted..."); // Sort - alphabetically for the primary key, reverse alphabetically for the second var primarySort = new CKQuery(recordType, NSPredicate.PredicateWithValue(true)); primarySort.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor(primaryFieldKey, true), new NSSortDescriptor(secondaryFieldKey, false) }; database.PerformQuery(primarySort, null, OnQuery); }
public async override Task <Results> Run() { var location = Location; if (location == null) { return(null); } var container = CKContainer.DefaultContainer; var publicDB = container.PublicCloudDatabase; var query = new CKQuery("Items", NSPredicate.FromValue(true)) { SortDescriptors = new NSSortDescriptor [] { new CKLocationSortDescriptor("location", location) } }; var defaultZoneId = new CKRecordZoneID(CKRecordZone.DefaultName, CKContainer.OwnerDefaultName); CKRecord [] recordArray = await publicDB.PerformQueryAsync(query, defaultZoneId); var results = new Results(alwaysShowAsList: true); var len = recordArray.Length; if (len == 0) { ListHeading = "No matching items"; } else if (len == 1) { ListHeading = "Found 1 matching item:"; } else { ListHeading = $"Found {recordArray.Length} matching items:"; } results.Items.AddRange(recordArray.Select(r => new CKRecordWrapper(r))); return(results); }
CKQuery CreatePostQuery() { // Create predicate out of tags. If self.tagArray is empty we should get every post NSPredicate[] subPredicates = new NSPredicate[tagArray.Length]; for (int i = 0; i < tagArray.Length; i++) { subPredicates [i] = Utils.CreateTagPredicate(tagArray [i]); } // If our tagArray is empty, create a true predicate (as opposed to a predicate containing "Tags CONTAINS ''" NSPredicate finalPredicate = tagArray.Length == 0 ? NSPredicate.FromValue(true) : NSCompoundPredicate.CreateAndPredicate(subPredicates); CKQuery postQuery = new CKQuery(Post.RecordType, finalPredicate); // lastest post on the top postQuery.SortDescriptors = Utils.CreateCreationDateDescriptor(ascending: false); return(postQuery); }
async Task DeletePastPurchasesAsync() { try { var container = CKContainer.DefaultContainer; var db = container.PrivateCloudDatabase; var pred = NSPredicate.FromFormat("TransactionId != 'tttt'"); var query = new CKQuery("PatronSubscription", pred); var recs = await db.PerformQueryAsync(query, CKRecordZone.DefaultRecordZone().ZoneId); Console.WriteLine("NUM RECS = {0}", recs.Length); foreach (var r in recs) { await db.DeleteRecordAsync(r.Id); } } catch (NSErrorException ex) { Console.WriteLine("ERROR: {0}", ex.Error); Log.Error(ex); } catch (Exception ex) { Log.Error(ex); } }
async Task DeletePastPurchasesAsync () { try { var container = CKContainer.DefaultContainer; var db = container.PrivateCloudDatabase; var pred = NSPredicate.FromFormat ("TransactionId != 'tttt'"); var query = new CKQuery ("PatronSubscription", pred); var recs = await db.PerformQueryAsync (query, CKRecordZone.DefaultRecordZone().ZoneId); Console.WriteLine ("NUM RECS = {0}", recs.Length); foreach (var r in recs) { await db.DeleteRecordAsync (r.Id); } } catch (NSErrorException ex) { Console.WriteLine ("ERROR: {0}", ex.Error); Log.Error (ex); } catch (Exception ex) { Log.Error (ex); } }
CKQuery CreateLoadNewPostQuery() { // Creates predicate based on tag string and most recent post from server NSPredicate predicate = CreateLoadNewPostPredicate (); var postQuery = new CKQuery (Post.RecordType, predicate); postQuery.SortDescriptors = Utils.CreateCreationDateDescriptor (ascending: true); return postQuery; }
CKQuery CreatePostQuery() { // Create predicate out of tags. If self.tagArray is empty we should get every post NSPredicate[] subPredicates = new NSPredicate[tagArray.Length]; for (int i = 0; i < tagArray.Length; i++) subPredicates [i] = Utils.CreateTagPredicate(tagArray [i]); // If our tagArray is empty, create a true predicate (as opposed to a predicate containing "Tags CONTAINS ''" NSPredicate finalPredicate = tagArray.Length == 0 ? NSPredicate.FromValue (true) : NSCompoundPredicate.CreateAndPredicate (subPredicates); CKQuery postQuery = new CKQuery (Post.RecordType, finalPredicate); // lastest post on the top postQuery.SortDescriptors = Utils.CreateCreationDateDescriptor (ascending: false); return postQuery; }
public void QueryForRecords (string referenceRecordName, Action<List<CKRecord>> completionHandler) { var recordId = new CKRecordID (referenceRecordName); var parent = new CKReference (recordId, CKReferenceAction.None); var predicate = NSPredicate.FromFormat ("parent == %@", parent); var query = new CKQuery (ReferenceSubItemsRecordType, predicate) { SortDescriptors = new [] { new NSSortDescriptor ("creationDate", false) } }; var queryOperation = new CKQueryOperation (query) { DesiredKeys = new [] { NameField } }; var results = new List<CKRecord> (); queryOperation.RecordFetched = (record) => results.Add (record); queryOperation.Completed = (cursor, error) => { if (error != null) { Console.WriteLine ("An error occured: {0}", error.Description); return; } DispatchQueue.MainQueue.DispatchAsync (() => completionHandler (results)); }; publicDatabase.AddOperation (queryOperation); }
public void SetUp() { TestRuntime.AssertXcodeVersion(6, 0); q = new CKQuery("Foo", NSPredicate.FromFormat("email = '@xamarin'")); op = new CKQueryOperation(q); }
void LoadImages() { // If we're already loading a set of images or there are no images left to load, just return lock (locker) { if (isLoadingBatch || firstThumbnailLoaded) { return; } else { isLoadingBatch = true; } } // If we have a cursor, continue where we left off, otherwise set up new query CKQueryOperation queryOp = null; if (imageCursor != null) { queryOp = new CKQueryOperation(imageCursor); } else { CKQuery thumbnailQuery = new CKQuery(Image.RecordType, NSPredicate.FromValue(true)); thumbnailQuery.SortDescriptors = Utils.CreateCreationDateDescriptor(ascending: false); queryOp = new CKQueryOperation(thumbnailQuery); } // We only want to download the thumbnails, not the full image queryOp.DesiredKeys = new string[] { Image.ThumbnailKey }; queryOp.ResultsLimit = UpdateBy; queryOp.RecordFetched = (CKRecord record) => { ImageCollection.AddImageFromRecord(record); InvokeOnMainThread(() => { loadingImages.StopAnimating(); ImageCollection.ReloadData(); }); }; queryOp.Completed = (CKQueryCursor cursor, NSError error) => { Error errorResponse = HandleError(error); if (errorResponse == Error.Success) { imageCursor = cursor; isLoadingBatch = false; if (cursor == null) { firstThumbnailLoaded = true; // If cursor is nil, lock this method indefinitely (all images have been loaded) } } else if (errorResponse == Error.Retry) { // If there's no specific number of seconds we're told to wait, default to 3 Utils.Retry(() => { // Resets so we can load images again and then goes to load isLoadingBatch = false; LoadImages(); }, error); } else if (errorResponse == Error.Ignore) { // If we get an ignore error they're not often recoverable. I'll leave loadImages locked indefinitely (this is up to the developer) Console.WriteLine("Error: {0}", error.Description); string errorTitle = "Error"; string dismissButton = "Okay"; string errorMessage = "We couldn't fetch one or more of the thumbnails"; UIAlertController alert = UIAlertController.Create(errorTitle, errorMessage, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create(dismissButton, UIAlertActionStyle.Cancel, null)); InvokeOnMainThread(() => PresentViewController(alert, true, null)); } }; PublicCloudDatabase.AddOperation(queryOp); }
void LoadImages() { // If we're already loading a set of images or there are no images left to load, just return lock (locker) { if (isLoadingBatch || firstThumbnailLoaded) return; else isLoadingBatch = true; } // If we have a cursor, continue where we left off, otherwise set up new query CKQueryOperation queryOp = null; if (imageCursor != null) { queryOp = new CKQueryOperation (imageCursor); } else { CKQuery thumbnailQuery = new CKQuery (Image.RecordType, NSPredicate.FromValue (true)); thumbnailQuery.SortDescriptors = Utils.CreateCreationDateDescriptor (ascending: false); queryOp = new CKQueryOperation (thumbnailQuery); } // We only want to download the thumbnails, not the full image queryOp.DesiredKeys = new string[] { Image.ThumbnailKey }; queryOp.ResultsLimit = UpdateBy; queryOp.RecordFetched = (CKRecord record) => { ImageCollection.AddImageFromRecord (record); InvokeOnMainThread (() => { loadingImages.StopAnimating (); ImageCollection.ReloadData (); }); }; queryOp.Completed = (CKQueryCursor cursor, NSError error) => { Error errorResponse = HandleError (error); if (errorResponse == Error.Success) { imageCursor = cursor; isLoadingBatch = false; if (cursor == null) firstThumbnailLoaded = true; // If cursor is nil, lock this method indefinitely (all images have been loaded) } else if (errorResponse == Error.Retry) { // If there's no specific number of seconds we're told to wait, default to 3 Utils.Retry (() => { // Resets so we can load images again and then goes to load isLoadingBatch = false; LoadImages (); }, error); } else if (errorResponse == Error.Ignore) { // If we get an ignore error they're not often recoverable. I'll leave loadImages locked indefinitely (this is up to the developer) Console.WriteLine ("Error: {0}", error.Description); string errorTitle = "Error"; string dismissButton = "Okay"; string errorMessage = "We couldn't fetch one or more of the thumbnails"; UIAlertController alert = UIAlertController.Create (errorTitle, errorMessage, UIAlertControllerStyle.Alert); alert.AddAction (UIAlertAction.Create (dismissButton, UIAlertActionStyle.Cancel, null)); InvokeOnMainThread (() => PresentViewController (alert, true, null)); } }; PublicCloudDatabase.AddOperation (queryOp); }