Ejemplo n.º 1
0
 public void Default()
 {
     using (var moc = new NSManagedObjectContext()) {
         Assert.That(moc.ConcurrencyType, Is.EqualTo(NSManagedObjectContextConcurrencyType.Confinement), "ConcurrencyType");
         Default(moc);
     }
 }
Ejemplo n.º 2
0
 public void Perform_Null()
 {
     using (var moc = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.MainQueue)) {
         // a NULL results in a native crash - but not immediate
         moc.Perform(null);
     }
 }
Ejemplo n.º 3
0
 public void Main()
 {
     using (var moc = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.MainQueue)) {
         Assert.That(moc.ConcurrencyType, Is.EqualTo(NSManagedObjectContextConcurrencyType.MainQueue), "ConcurrencyType");
         Default(moc);
     }
 }
Ejemplo n.º 4
0
 public void PerformAndWait_Null()
 {
     using (var moc = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.MainQueue)) {
         // a NULL results in a *immediate* native crash
         Assert.Throws <ArgumentNullException> (() => moc.PerformAndWait(null));
     }
 }
		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;
		}
Ejemplo n.º 6
0
 public void PerformAndWait_Null()
 {
     using (var moc = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.MainQueue)) {
         // a NULL results in a *immediate* native crash
         moc.PerformAndWait(null);
     }
 }
Ejemplo n.º 7
0
		public override void Main ()
		{
			base.Main ();

			managedObjectContext = new NSManagedObjectContext () {
				PersistentStoreCoordinator = sharedPSC
			};

			Parse (earthquakeData);
		}
Ejemplo n.º 8
0
        public override void Main()
        {
            base.Main();

            managedObjectContext = new NSManagedObjectContext()
            {
                PersistentStoreCoordinator = sharedPSC
            };

            Parse(earthquakeData);
        }
Ejemplo n.º 9
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");
             }
         }
 }
 void Default(NSManagedObjectContext moc)
 {
     Assert.That(moc.DeletedObjects.Count, Is.EqualTo((nuint)0), "DeletedObjects");
     Assert.False(moc.HasChanges, "HasChanges");
     Assert.That(moc.InsertedObjects.Count, Is.EqualTo((nuint)0), "InsertedObjects");
     Assert.That(moc.MergePolicy, Is.Not.EqualTo(IntPtr.Zero), "MergePolicy");
     Assert.Null(moc.ParentContext, "ParentContext");
     Assert.Null(moc.PersistentStoreCoordinator, "PersistentStoreCoordinator");
     Assert.That(moc.RegisteredObjects.Count, Is.EqualTo((nuint)0), "RegisteredObjects");
     Assert.False(moc.RetainsRegisteredObjects, "RetainsRegisteredObjects");
     Assert.That(moc.StalenessInterval, Is.EqualTo(-1), "StalenessInterval");
     Assert.Null(moc.UndoManager, "UndoManager");
     Assert.That(moc.UpdatedObjects.Count, Is.EqualTo((nuint)0), "UpdatedObjects");
     Assert.That(moc.UserInfo.Count, Is.EqualTo((nuint)0), "UserInfo");
 }
Ejemplo n.º 11
0
        /// The managed object context for the view controller (which is bound to the persistent store coordinator for the application).
        NSManagedObjectContext CreatePrivateQueueContext(out NSError error)
        {
            // It uses the same store and model, but a new persistent store coordinator and context.
            var localCoordinator    = new NSPersistentStoreCoordinator(CoreDataStackManager.SharedManager.ManagedObjectModel);
            NSPersistentStore store = localCoordinator.AddPersistentStoreWithType(NSPersistentStoreCoordinator.SQLiteStoreType, null, CoreDataStackManager.SharedManager.StoreURL, null, out error);

            if (store == null)
            {
                return(null);
            }

            var context = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.PrivateQueue);

            context.PersistentStoreCoordinator = localCoordinator;
            context.UndoManager = null;
            return(context);
        }
Ejemplo n.º 12
0
 void Default(NSManagedObjectContext moc)
 {
     Assert.That(moc.DeletedObjects.Count, Is.EqualTo((nuint)0), "DeletedObjects");
     Assert.False(moc.HasChanges, "HasChanges");
     Assert.That(moc.InsertedObjects.Count, Is.EqualTo((nuint)0), "InsertedObjects");
     Assert.That(moc.MergePolicy, Is.Not.EqualTo(IntPtr.Zero), "MergePolicy");
     Assert.Null(moc.ParentContext, "ParentContext");
     Assert.Null(moc.PersistentStoreCoordinator, "PersistentStoreCoordinator");
     Assert.That(moc.RegisteredObjects.Count, Is.EqualTo((nuint)0), "RegisteredObjects");
     Assert.False(moc.RetainsRegisteredObjects, "RetainsRegisteredObjects");
     Assert.That(moc.StalenessInterval, Is.EqualTo(-1), "StalenessInterval");
     if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 12, throwIfOtherPlatform: false))
     {
         Assert.Null(moc.UndoManager, "UndoManager");
     }
     else
     {
         Assert.NotNull(moc.UndoManager, "UndoManager");
     }
     Assert.That(moc.UpdatedObjects.Count, Is.EqualTo((nuint)0), "UpdatedObjects");
     Assert.That(moc.UserInfo.Count, Is.EqualTo((nuint)0), "UserInfo");
 }
Ejemplo n.º 13
0
 public EditProductView(Product product, NSManagedObjectContext context, bool isNewProduct = false) : base("EditProductView", null)
 {
     this._context     = context;
     this._product     = product;
     this.isNewProduct = isNewProduct;
 }
Ejemplo n.º 14
0
 public void UndoManager_Null()
 {
     using (var moc = new NSManagedObjectContext(NSManagedObjectContextConcurrencyType.MainQueue)) {
         moc.UndoManager = null;
     }
 }
Ejemplo n.º 15
0
		/// The managed object context for the view controller (which is bound to the persistent store coordinator for the application).
		NSManagedObjectContext CreatePrivateQueueContext (out NSError error)
		{
			// It uses the same store and model, but a new persistent store coordinator and context.
			var localCoordinator = new NSPersistentStoreCoordinator (CoreDataStackManager.SharedManager.ManagedObjectModel);
			NSPersistentStore store = localCoordinator.AddPersistentStoreWithType (NSPersistentStoreCoordinator.SQLiteStoreType, null, CoreDataStackManager.SharedManager.StoreURL, null, out error);

			if (store == null)
				return null;

			var context = new NSManagedObjectContext (NSManagedObjectContextConcurrencyType.PrivateQueue);
			context.PersistentStoreCoordinator = localCoordinator;
			context.UndoManager = null;
			return context;
		}
 public static Photo InsertNewObject(NSManagedObjectContext context)
 {
     return (Photo) NSEntityDescription.InsertNewObjectForEntityForName("Photo", context);
 }
Ejemplo n.º 17
0
 //New Product
 public Product(NSManagedObjectContext context)
 {
     this._managedObject = CreateNewBook(context);
 }
Ejemplo n.º 18
0
 private static NSManagedObject CreateNewBook(NSManagedObjectContext context)
 {
     return((NSManagedObject)NSEntityDescription.InsertNewObjectForEntityForName(EntityName(), context));
 }
Ejemplo n.º 19
0
 public ManagedEarthquake(NSEntityDescription description, NSManagedObjectContext context) : base(description, context)
 {
     this.IsDirectBinding = true;
 }
Ejemplo n.º 20
0
        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();
        }
Ejemplo n.º 21
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");
                    }
                }
            }
        }
Ejemplo n.º 22
0
 public ManagedEarthquake(NSEntityDescription description, NSManagedObjectContext context)
     : base(description, context)
 {
     this.IsDirectBinding = true;
 }