public static Photographer WithName(string name, NSManagedObjectContext context)
		{
			Photographer photographer = null;
			// This is just like Photo(Flickr)'s method.  Look there for commentary.
			if (name.Length > 0)
			{
				var request = new NSFetchRequest("Photographer")
				{
					SortDescriptors = new[] {new NSSortDescriptor("name", true, new Selector("localizedCaseInsensitiveCompare:"))},
					Predicate =  NSPredicate.FromFormat("name = %@", new NSObject[] {(NSString) name})
				};
				NSError error;
				var matches = context.ExecuteFetchRequest(request, out error);
				if (matches == null || matches.Length > 1)
				{
					// handle error
				}
				else if (matches.Length == 0)
				{
					photographer = InsertNewObject(context);
					photographer.Name = name;
				}
				else
				{
					photographer = (Photographer) matches.First();
				}
			}
			return photographer;
		}
 public void CtorString()
 {
     using (var fr = new NSFetchRequest("entityName")) {
         Assert.That(fr.EntityName, Is.EqualTo("entityName"), "EntityName");
         // Entity is invalid (and throws) so we do not check it - except to see if we can set it to null
         fr.Entity = null;
         Assert.Null(fr.Entity, "Entity");
     }
 }
        private void AddEarthquakesToList(List<Earthquake> earthquakes)
        {
            var entity = NSEntityDescription.EntityForName ("Earthquake", managedObjectContext);
            var fetchRequest = new NSFetchRequest ();
            fetchRequest.Entity = entity;

            var date = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("date"));
            var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("location"));

            fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location };
            fetchRequest.ResultType = NSFetchRequestResultType.DictionaryResultType;

            NSError error;

            foreach (var earthquake in earthquakes) {
                var arguments = new NSObject[] { earthquake.Location, earthquake.Date };
                fetchRequest.Predicate = NSPredicate.FromFormat (@"location = %@ AND date = %@", arguments);
                var fetchedItems = NSArray.FromNSObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));

                if (fetchedItems.Count == 0) {

                    if (string.IsNullOrEmpty (entity.Description))
                        continue;

                    var managedEarthquake = new ManagedEarthquake (entity, managedObjectContext) {
                        Magnitude = earthquake.Magnitude,
                        Location = earthquake.Location,
                        Date = earthquake.Date,
                        USGSWebLink = earthquake.USGSWebLink,
                        Latitude = earthquake.Latitude,
                        Longitude = earthquake.Longitude
                    };

                    managedObjectContext.InsertObject (managedEarthquake);
                }

                var gregorian = new NSCalendar (NSCalendarType.Gregorian);
                var offsetComponents = new NSDateComponents ();
                offsetComponents.Day = -14;// 14 days back from today
                NSDate twoWeeksAgo = gregorian.DateByAddingComponents (offsetComponents, NSDate.Now, NSCalendarOptions.None);

                // use the same fetchrequest instance but switch back to NSManagedObjectResultType
                fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject;
                fetchRequest.Predicate = NSPredicate.FromFormat (@"date < %@", new NSObject[] { twoWeeksAgo });

                var olderEarthquakes = NSArray.FromObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));

                for (int i = 0; i < olderEarthquakes.Count; i++) {
                    managedObjectContext.DeleteObject (olderEarthquakes.GetItem<ManagedEarthquake> (i));
                }

                if (managedObjectContext.HasChanges) {
                    if (!managedObjectContext.Save (out error))
                        Console.WriteLine (string.Format ("Unresolved error {0}", error.LocalizedDescription));
                }
            }
        }
Esempio n. 4
0
 public void PerformFetch_Minimal()
 {
     using (NSManagedObjectContext c = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.PrivateQueue))
         using (NSFetchRequest r = new NSFetchRequest()) {
             r.SortDescriptors = new NSSortDescriptor[] {
                 new NSSortDescriptor("key", true)
             };
             r.Entity = new NSEntityDescription();
             using (NSFetchedResultsController frc = new NSFetchedResultsController(r, c, null, null)) {
                 NSError e;
                 Assert.False(frc.PerformFetch(out e), "PerformFetch");
             }
         }
 }
 public void SettersNull()
 {
     using (var fr = new NSFetchRequest()) {
         // bug #18153
         fr.Predicate = null;
         // bug #18152
         fr.SortDescriptors = null;
         // other properties that are null (by default) are likely accepting being set to null
         fr.AffectedStores      = fr.AffectedStores;
         fr.HavingPredicate     = fr.HavingPredicate;
         fr.PropertiesToGroupBy = fr.PropertiesToGroupBy;
         fr.RelationshipKeyPathsForPrefetching = fr.RelationshipKeyPathsForPrefetching;
     }
 }
        private void FetchCoreData()
        {
            NSError        error   = null;
            NSFetchRequest request = new NSFetchRequest("Product");

            NSObject[] results = Context.ExecuteFetchRequest(request, out error);
            Products = new List <Product>();
            foreach (var r in results)
            {
                Products.Add(new Product((NSManagedObject)r));
            }
            productsTable.ReloadData();
            //Context.ExecuteFetchRequest(FetchController.FetchRequest, out error);
        }
        /// Fetch quakes ordered in time and reload the table view.
        void ReloadTableView()
        {
            NSFetchRequest request = NSFetchRequest.FromEntityName("Quake");

            request.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("time", false) };

            NSError anyError;

            NSObject[] fetchedQuakes = ManagedObjectContext.ExecuteFetchRequest(request, out anyError);

            if (fetchedQuakes == null)
            {
                Console.WriteLine("Error fetching: {0}", anyError.LocalizedDescription);
                return;
            }

            var quakes = Array.ConvertAll(fetchedQuakes, item => (Quake)item).ToList <Quake> ();

            tableView.Source = new QuakeTableSourse(quakes);
            tableView.ReloadData();
        }
 public void DefaultValues()
 {
     using (var fr = new NSFetchRequest()) {
         Assert.Null(fr.AffectedStores, "AffectedStores");
         Assert.Null(fr.Entity, "Entity");
         Assert.Null(fr.EntityName, "EntityName");
         Assert.That(fr.FetchBatchSize, Is.EqualTo((nint)0), "FetchBatchSize");
         Assert.That(fr.FetchLimit, Is.EqualTo((nuint)0), "FetchLimit");
         Assert.That(fr.FetchOffset, Is.EqualTo((nuint)0), "FetchOffset");
         Assert.Null(fr.HavingPredicate, "HavingPredicate");
         Assert.True(fr.IncludesPendingChanges, "IncludesPendingChanges");
         Assert.True(fr.IncludesPropertyValues, "IncludesPropertyValues");
         Assert.True(fr.IncludesSubentities, "IncludesSubentities");
         Assert.Null(fr.Predicate, "Predicate");
         Assert.Null(fr.PropertiesToFetch, "PropertiesToFetch");
         Assert.Null(fr.PropertiesToGroupBy, "PropertiesToGroupBy");
         Assert.Null(fr.RelationshipKeyPathsForPrefetching, "RelationshipKeyPathsForPrefetching");
         Assert.That(fr.ResultType, Is.EqualTo(NSFetchRequestResultType.ManagedObject), "ResultType");
         Assert.False(fr.ReturnsDistinctResults, "ReturnsDistinctResults");
         Assert.True(fr.ReturnsObjectsAsFaults, "ReturnsObjectsAsFaults");
         Assert.False(fr.ShouldRefreshRefetchedObjects, "ShouldRefreshRefetchedObjects");
         Assert.Null(fr.SortDescriptors, "SortDescriptors");
     }
 }
Esempio n. 9
0
        public void Sections()
        {
            // https://bugzilla.xamarin.com/show_bug.cgi?id=13785

            // use Caches directory so this works with tvOS on devices (as well as existing iOS devices)
            string applicationDocumentsDirectory = NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true).LastOrDefault();

            using (var ManagedObjectModel = new NSManagedObjectModel()) {
                {
                    // create an entity description
                    NSEntityDescription entity = new NSEntityDescription();
                    entity.Name = "Earthquake";

                    // create an attribute for the entity
                    NSAttributeDescription date = new NSAttributeDescription();
                    date.AttributeType = NSAttributeType.Date;
                    date.Name          = "date";
                    date.Optional      = false;

                    NSAttributeDescription latitude = new NSAttributeDescription();
                    latitude.AttributeType = NSAttributeType.Double;
                    latitude.Name          = "latitude";
                    latitude.Optional      = false;

                    NSAttributeDescription location = new NSAttributeDescription();
                    location.AttributeType = NSAttributeType.String;
                    location.Name          = "location";
                    location.Optional      = false;

                    NSAttributeDescription longitude = new NSAttributeDescription();
                    longitude.AttributeType = NSAttributeType.Double;
                    longitude.Name          = "longitude";
                    longitude.Optional      = false;

                    NSAttributeDescription magnitude = new NSAttributeDescription();
                    magnitude.AttributeType = NSAttributeType.Float;
                    magnitude.Name          = "magnitude";
                    magnitude.Optional      = false;

                    NSAttributeDescription USGSWebLink = new NSAttributeDescription();
                    USGSWebLink.AttributeType = NSAttributeType.String;
                    USGSWebLink.Name          = "USGSWebLink";
                    USGSWebLink.Optional      = false;

                    // assign the properties to the entity
                    entity.Properties = new NSPropertyDescription[] {
                        date,
                        latitude,
                        location,
                        longitude,
                        magnitude,
                        USGSWebLink
                    };

                    // add the entity to the model, and then add a configuration that
                    // contains the entities
                    ManagedObjectModel.Entities = new NSEntityDescription[] { entity };
                    ManagedObjectModel.SetEntities(ManagedObjectModel.Entities, String.Empty);
                }

                using (var PersistentStoreCoordinator = new NSPersistentStoreCoordinator(ManagedObjectModel)) {
                    {
                        var     storePath = applicationDocumentsDirectory + "/Earthquakes.sqlite";
                        var     storeUrl  = new NSUrl(storePath, false);
                        NSError error;

                        if (PersistentStoreCoordinator.AddPersistentStoreWithType(NSPersistentStoreCoordinator.SQLiteStoreType, null, storeUrl, null, out error) == null)
                        {
                            Assert.Fail("Unresolved error " + error + ", " + error.UserInfo);
                        }
                    }

                    using (var ManagedObjectContext = new NSManagedObjectContext()) {
                        ManagedObjectContext.PersistentStoreCoordinator = PersistentStoreCoordinator;

                        //					NSNotificationCenter.DefaultCenter.AddObserver (
                        //						this, new MonoTouch.ObjCRuntime.Selector ("mergeChanges"),
                        //						"NSManagedObjectContextDidSaveNotification", null);


                        NSFetchRequest      fetchRequest = new NSFetchRequest();
                        NSEntityDescription entity       = NSEntityDescription.EntityForName("Earthquake", ManagedObjectContext);
                        fetchRequest.Entity = entity;

                        NSSortDescriptor sortDescriptor = new NSSortDescriptor("date", false);
                        fetchRequest.SortDescriptors = new [] { sortDescriptor };

                        NSFetchedResultsController fetchedResultsController = new NSFetchedResultsController(
                            fetchRequest, ManagedObjectContext, null, null);

                        NSError error;

                        if (!fetchedResultsController.PerformFetch(out error))
                        {
                            Assert.Fail("Unresolved error: " + error + ", " + error.UserInfo);
                        }

                        var sections = fetchedResultsController.Sections;
                        Assert.That(sections [0].GetType().FullName, Is.StringEnding("CoreData.NSFetchedResultsSectionInfoWrapper"), "Wrapper");
                    }
                }
            }
        }
        private void AddEarthquakesToList(List <Earthquake> earthquakes)
        {
            var entity       = NSEntityDescription.EntityForName("Earthquake", managedObjectContext);
            var fetchRequest = new NSFetchRequest();

            fetchRequest.Entity = entity;

            var date     = (NSPropertyDescription)entity.PropertiesByName.ValueForKey(new NSString("date"));
            var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey(new NSString("location"));

            fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location };
            fetchRequest.ResultType        = NSFetchRequestResultType.DictionaryResultType;

            NSError error;

            foreach (var earthquake in earthquakes)
            {
                var arguments = new NSObject[] { earthquake.Location, earthquake.Date };
                fetchRequest.Predicate = NSPredicate.FromFormat(@"location = %@ AND date = %@", arguments);
                var fetchedItems = NSArray.FromNSObjects(managedObjectContext.ExecuteFetchRequest(fetchRequest, out error));

                if (fetchedItems.Count == 0)
                {
                    if (string.IsNullOrEmpty(entity.Description))
                    {
                        continue;
                    }

                    var managedEarthquake = new ManagedEarthquake(entity, managedObjectContext)
                    {
                        Magnitude   = earthquake.Magnitude,
                        Location    = earthquake.Location,
                        Date        = earthquake.Date,
                        USGSWebLink = earthquake.USGSWebLink,
                        Latitude    = earthquake.Latitude,
                        Longitude   = earthquake.Longitude
                    };

                    managedObjectContext.InsertObject(managedEarthquake);
                }

                var gregorian        = new NSCalendar(NSCalendarType.Gregorian);
                var offsetComponents = new NSDateComponents();
                offsetComponents.Day = -14;                // 14 days back from today
                NSDate twoWeeksAgo = gregorian.DateByAddingComponents(offsetComponents, NSDate.Now, NSCalendarOptions.None);

                // use the same fetchrequest instance but switch back to NSManagedObjectResultType
                fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject;
                fetchRequest.Predicate  = NSPredicate.FromFormat(@"date < %@", new NSObject[] { twoWeeksAgo });

                var olderEarthquakes = NSArray.FromObjects(managedObjectContext.ExecuteFetchRequest(fetchRequest, out error));

                for (int i = 0; i < olderEarthquakes.Count; i++)
                {
                    managedObjectContext.DeleteObject(olderEarthquakes.GetItem <ManagedEarthquake> (i));
                }

                if (managedObjectContext.HasChanges)
                {
                    if (!managedObjectContext.Save(out error))
                    {
                        Console.WriteLine(string.Format("Unresolved error {0}", error.LocalizedDescription));
                    }
                }
            }
        }
        void FetchQuakes(object sender, EventArgs e)
        {
            fetchQuakesButton.Enabled = false;
            var jsonURL           = new NSUrl("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
            var session           = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.EphemeralSessionConfiguration);
            NSUrlSessionTask task = session.CreateDataTask(jsonURL, (data, response, error) => {
                if (data == null)
                {
                    Console.WriteLine("Error connecting: {0}", error.LocalizedDescription);
                    return;
                }

                NSError anyError;
                NSManagedObjectContext taskContext = CreatePrivateQueueContext(out anyError);
                var jsonDictionary = NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, out anyError);

                if (jsonDictionary == null)
                {
                    Console.WriteLine("Error creating JSON dictionary: {0}", anyError.LocalizedDescription);
                    return;
                }

                var featuresArray     = (NSArray)jsonDictionary.ValueForKey((NSString)"features");
                int totalFeatureCount = (int)featuresArray.Count;

                int numBatches = totalFeatureCount / BatchSize;
                numBatches    += totalFeatureCount % BatchSize > 0 ? 1 : 0;
                for (int batchNumber = 0; batchNumber < numBatches; batchNumber++)
                {
                    int rangeStart  = batchNumber * BatchSize;
                    int rangeLength = Math.Min(BatchSize, totalFeatureCount - batchNumber * BatchSize);

                    NSArray featuresBatchArray = featuresArray.SubarrayWithRange(new NSRange(rangeStart, rangeLength));
                    // Create a request to fetch existing quakes with the same codes as those in the JSON data.
                    // Existing quakes will be updated with new data; if there isn't a match, then create a new quake to represent the event.
                    NSFetchRequest matchingQuakeRequest = NSFetchRequest.FromEntityName("Quake");

                    // Get the codes for each of the features and store them in an array.
                    NSArray codesDump = (NSArray)featuresBatchArray.ValueForKeyPath((NSString)"properties.code");

                    matchingQuakeRequest.Predicate = NSPredicate.FromFormat("code in %@", codesDump);
                    var rawFetch = taskContext.ExecuteFetchRequest(matchingQuakeRequest, out anyError);
                    Quake[] allMatchingQuakes = Array.ConvertAll(rawFetch, item => (Quake)item);
                    NSString[] codes          = NSArray.FromArray <NSString> (codesDump);

                    for (int k = 0; k < codes.Length; k++)
                    {
                        var code           = codes [k];
                        var matchingQuakes = allMatchingQuakes.Where(q => q.Code == code).ToArray <Quake> ();

                        Quake quake = null;

                        int matchingLength = matchingQuakes.Length;
                        switch (matchingLength)
                        {
                        case 0:
                            //Insert new item
                            quake = (Quake)NSEntityDescription.InsertNewObjectForEntityForName("Quake", taskContext);
                            break;

                        case 1:
                            //Update existing item
                            quake = matchingQuakes [0];
                            break;

                        default:
                            //Remove duplicates
                            for (int i = 1; i < matchingQuakes.Length; i++)
                            {
                                taskContext.DeleteObject(matchingQuakes [i]);
                            }

                            quake = matchingQuakes [0];
                            break;
                        }

                        var result          = featuresBatchArray.GetItem <NSDictionary> ((nuint)k);
                        var quakeDictionary = (NSDictionary)result.ObjectForKey((NSString)"properties");
                        quake.UpdateFromDictionary(quakeDictionary);
                    }

                    if (!taskContext.Save(out anyError))
                    {
                        Console.WriteLine("Error saving batch: {0}", anyError.LocalizedDescription);
                        return;
                    }

                    taskContext.Reset();
                }

                // Bounce back to the main queue to reload the table view and reenable the fetch button.
                NSOperationQueue.MainQueue.AddOperation(() => {
                    ReloadTableView();
                    fetchQuakesButton.Enabled = true;
                });
            });

            task.Resume();
        }