示例#1
0
        private object GetReferencedObject(Realm realm, JsonReader reader, Type objectType)
        {
            KeyType keyType;

            if (!_keyTypes.TryGetValue(objectType.Name, out keyType))
            {
                keyType = GetKeyType(realm, objectType);
                _keyTypes[objectType.Name] = keyType;
            }

            if (keyType == KeyType.String)
            {
                var key = reader.Value.ToString();
                var referencedObject = realm.Find(objectType.Name, key);
                return(referencedObject);
            }
            else if (keyType == KeyType.Int)
            {
                var key = (long)reader.Value;
                var referencedObject = realm.Find(objectType.Name, key);
                return(referencedObject);
            }

            throw new NotImplementedException($"Key type {keyType} is not supported");
        }
示例#2
0
            public RemoteViews GetViewAt(int position)
            {
                Realm other = Realm.GetInstance(DB.RealmConfiguration);

                if (!RealmInstance.IsSameInstance(other))
                {
                    RealmInstance.Dispose();
                    RealmInstance = other;
                }

                RemoteViews page = new RemoteViews(context.PackageName, ItemLayout);

                Chapter chapter = Descending ? RealmInstance.Find <Chapter>(FirstChapterId + Count - 1 - position)
                    : RealmInstance.Find <Chapter>(FirstChapterId + position);

                if (chapter == null)
                {
                    return(page);
                }

                page.SetTextViewText(Resource.Id.chapter_title, chapter.Title);

                Intent chapterClick = new Intent();

                chapterClick.SetData(Uri.Parse(chapter.URL));
                page.SetOnClickFillInIntent(Resource.Id.root, chapterClick);

                return(page);
            }
示例#3
0
        protected override void Populate(ScoreInfo model, ArchiveReader?archive, Realm realm, CancellationToken cancellationToken = default)
        {
            // Ensure the beatmap is not detached.
            if (!model.BeatmapInfo.IsManaged)
            {
                model.BeatmapInfo = realm.Find <BeatmapInfo>(model.BeatmapInfo.ID);
            }

            if (!model.Ruleset.IsManaged)
            {
                model.Ruleset = realm.Find <RulesetInfo>(model.Ruleset.ShortName);
            }

            // These properties are known to be non-null, but these final checks ensure a null hasn't come from somewhere (or the refetch has failed).
            // Under no circumstance do we want these to be written to realm as null.
            if (model.BeatmapInfo == null)
            {
                throw new ArgumentNullException(nameof(model.BeatmapInfo));
            }
            if (model.Ruleset == null)
            {
                throw new ArgumentNullException(nameof(model.Ruleset));
            }

            if (string.IsNullOrEmpty(model.StatisticsJson))
            {
                model.StatisticsJson = JsonConvert.SerializeObject(model.Statistics);
            }
        }
        public bool Set(string key, string value)
        {
            bool result = false;

            try
            {
                _realmInstance.Write(() =>
                {
                    var paramObject = _realmInstance.Find <Parameter>(key);
                    if (paramObject != null)
                    {
                        _realmInstance.Remove(paramObject);
                    }
                    _realmInstance.Add(new Parameter()
                    {
                        KeyName = key, Value = value
                    });
                });
                result = true;
            }
            catch (Exception e)
            {
                HandleError.Process("ParameterManager", "Set", e, false);
            }
            return(result);
        }
示例#5
0
    private void Start()
    {
        metal   = realm.Find <Resource>(Resource.Type.Metal.ToString());
        crystal = realm.Find <Resource>(Resource.Type.Crystal.ToString());
        workers = realm.Find <Unit>(Unit.Type.Worker.ToString());

        UpdateData();
    }
示例#6
0
 public void SaveEventWithSetReminder(int eventId)
 {
     db.Write(() =>
     {
         var eventreminder = db.Find("EventReminder", eventId) as EventReminder;
         eventreminder.NotificationEnabled = true;
         db.Add(eventreminder, true);
     });
 }
示例#7
0
    private void Start()
    {
        metal   = realm.Find <Resource>(Resource.Type.Metal.ToString());
        crystal = realm.Find <Resource>(Resource.Type.Crystal.ToString());

        workers.PropertyChanged += WorkersPropertyChangedListener;

        UpdateText();
    }
示例#8
0
        private async AsyncTask LoadProjects()
        {
            try
            {
                var syncConfig = new SyncConfiguration(
                    $"user={ App.RealmApp.CurrentUser.Id }",
                    App.RealmApp.CurrentUser);
                // :code-block-start:user-realm-config
                // :state-start: final
                userRealm = await Realm.GetInstanceAsync(syncConfig);

                // :state-end: :state-uncomment-start: start
                //// TODO: instatiate the userRealm by calling GetInstanceAsync
                //// userRealm = await ...
                // :state-uncomment-end:
                // :code-block-end:
                // :code-block-start:find-user
                // :state-start: final
                user = userRealm.Find <User>(App.RealmApp.CurrentUser.Id);
                // :state-end: :state-uncomment-start: start
                //// TODO: find the user in the userRealm
                //// Because the user's ID is the Primary Key, we can easily
                //// find the user by passing the ID to userRealm.Find<User>().
                //// user = ...
                // :state-uncomment-end:
                // :code-block-end:

                if (user == null && !Constants.AlreadyWarnedAboutBackendSetup)
                {
                    // Either the trigger hasn't completed yet, has failed,
                    // or was never created on the backend
                    // So let's wait a few seconds and check again...
                    await System.Threading.Tasks.Task.Delay(5000);

                    user = userRealm.Find <User>(App.RealmApp.CurrentUser.Id);
                    if (user == null)
                    {
                        Console.WriteLine("NO USER OBJECT: This error occurs if " +
                                          "you do not have the trigger configured on the backend " +
                                          "or when there is a network connectivity issue. See " +
                                          "https://www.mongodb.com/docs/realm/tutorial/realm-app/#triggers");

                        await DisplayAlert("No User object",
                                           "The User object for this user was not found on the server. " +
                                           "If this is a new user acocunt, the backend trigger may not have completed, " +
                                           "or the tirgger doesn't exist. Check your backend set up and logs.", "OK");

                        Constants.AlreadyWarnedAboutBackendSetup = true;
                    }
                }
                SetUpProjectList();
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error Loading Projects", ex.Message, "OK");
            }
        }
示例#9
0
    private void Start()
    {
        building = realm.Find <Building>(resourceType.ToString());
        workers  = realm.Find <Unit>(Unit.Type.Worker.ToString());

        resource.PropertyChanged += ResourcePropertyChangedListener;
        building.PropertyChanged += BuildingPropertyChangedListener;

        RecalculateIncrementPerCycle();
    }
示例#10
0
        private static IMapper GetAutoMapper(Realm auditRealm)
        {
            var config = new MapperConfiguration(
                cfg =>
            {
                cfg.CreateMap <SpeakerEntity, Speaker>().AfterMap(
                    (src, dest) =>
                {
                    var speakerID       = src.Id;
                    var existingSpeaker = auditRealm.Find <Speaker>(speakerID);
                    if (existingSpeaker != null)
                    {
                        dest.Avatar = existingSpeaker.Avatar;
                    }
                });
                cfg.CreateMap <VenueEntity, Venue>();
                cfg.CreateMap <FriendEntity, Friend>();
                cfg.CreateMap <CommunityEntity, Community>();
                cfg.CreateMap <TalkEntity, Talk>().AfterMap(
                    (src, dest) =>
                {
                    foreach (string speakerId in src.SpeakerIds)
                    {
                        var speaker = auditRealm.Find <Speaker>(speakerId);

                        dest.Speakers.Add(speaker);
                    }
                });
                cfg.CreateMap <SessionEntity, Session>().AfterMap(
                    (src, dest) =>
                {
                    dest.Talk = auditRealm.Find <Talk>(src.TalkId);
                });
                cfg.CreateMap <MeetupEntity, Meetup>()
                .ForMember(
                    dest => dest.Sessions,
                    o => o.ResolveUsing((src, dest, sessions, context) => context.Mapper.Map(src.Sessions, dest.Sessions)))
                .AfterMap(
                    (src, dest) =>
                {
                    foreach (string friendId in src.FriendIds)
                    {
                        var friend = auditRealm.Find <Friend>(friendId);
                        dest.Friends.Add(friend);
                    }

                    dest.Venue = auditRealm.Find <Venue>(src.VenueId);
                });
            });

            return(config.CreateMapper());
        }
        private static void InitializeAudoMapper(Realm realm)
        {
            Mapper.Initialize(
                cfg =>
            {
                cfg.CreateMap <SpeakerEntity, Speaker>().AfterMap(
                    (src, dest) =>
                {
                    dest.Avatar = AuditHelper.LoadImage("speakers", src.Id, "avatar.jpg");
                });
                cfg.CreateMap <VenueEntity, Venue>();
                cfg.CreateMap <FriendEntity, Friend>().AfterMap(
                    (src, dest) =>
                {
                    var friendId = src.Id;

                    dest.LogoSmall = AuditHelper.LoadImage("friends", friendId, "logo.small.png");
                    dest.Logo      = AuditHelper.LoadImage("friends", friendId, "logo.png");
                });
                cfg.CreateMap <CommunityEntity, Community>();
                cfg.CreateMap <TalkEntity, Talk>().AfterMap(
                    (src, dest) =>
                {
                    foreach (string speakerId in src.SpeakerIds)
                    {
                        var speaker = realm.Find <Speaker>(speakerId);

                        dest.Speakers.Add(speaker);
                    }
                });
                cfg.CreateMap <SessionEntity, Session>().AfterMap(
                    (src, dest) =>
                {
                    dest.Talk = realm.Find <Talk>(src.TalkId);
                });
                cfg.CreateMap <MeetupEntity, Meetup>()
                .ForMember(
                    dest => dest.Sessions,
                    o => o.ResolveUsing((src, dest, sessions, context) => context.Mapper.Map(src.Sessions, dest.Sessions)))
                .AfterMap(
                    (src, dest) =>
                {
                    foreach (string friendId in src.FriendIds)
                    {
                        var friend = realm.Find <Friend>(friendId);
                        dest.Friends.Add(friend);
                    }

                    dest.Venue = realm.Find <Venue>(src.VenueId);
                });
            });
        }
示例#12
0
        public static RealmObject FindByPrimaryKey <TKey, T>(Realm realm, TKey primaryKey) where T : RealmObject
        {
            if (primaryKey is string)
            {
                return(realm.Find(typeof(T).Name, primaryKey as string));
            }

            if (primaryKey is long || primaryKey is long?)
            {
                return(realm.Find(typeof(T).Name, primaryKey as long?));
            }

            return(null);
        }
示例#13
0
        private T retrieveFromID(Realm realm)
        {
            var found = realm.Find <T>(ID);

            if (found == null)
            {
                // It may be that we access this from the update thread before a refresh has taken place.
                // To ensure that behaviour matches what we'd expect (the object *is* available), force
                // a refresh to bring in any off-thread changes immediately.
                realm.Refresh();
                found = realm.Find <T>(ID);
            }

            return(found);
        }
示例#14
0
        private async AsyncTask LoadProjects()
        {
            try
            {
                var syncConfig = new SyncConfiguration(
                    $"user={ App.RealmApp.CurrentUser.Id }",
                    App.RealmApp.CurrentUser);
                // :code-block-start:user-realm-config
                // :state-start: final
                userRealm = await Realm.GetInstanceAsync(syncConfig);

                // :state-end: :state-uncomment-start: start
                //// TODO: instatiate the userRealm by calling GetInstanceAsync
                //// userRealm = await ...
                // :state-uncomment-end:
                // :code-block-end:
                // :code-block-start:find-user
                // :state-start: final
                user = userRealm.Find <User>(App.RealmApp.CurrentUser.Id);
                // :state-end: :state-uncomment-start: start
                //// TODO: find the user in the userRealm
                //// Because the user's ID is the Primary Key, we can easily
                //// find the user by passing the ID to userRealm.Find<User>().
                // :state-uncomment-end:
                // :code-block-end:
                if (user != null)
                {
                    SetUpProjectList();
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error Loading Projects", ex.Message, "OK");
            }
        }
示例#15
0
        private static void CreateWorkOuts()
        {
            Realm realm = Realm.GetInstance(GetConfigurationBase());

            using (Transaction transaction = realm.BeginWrite())
            {
                try
                {
                    foreach (int code in WorkOuts.Keys)
                    {
                        WorkOut workOut = realm.Find <WorkOut>(code);

                        if (workOut == null)
                        {
                            workOut = CreateWorkOut(realm, code);
                        }
                    }

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("=== PROBLEM: {0}", ex.Message);
                    transaction.Rollback();
                }
                finally
                {
                    realm.Dispose();
                }
            }
        }
示例#16
0
        public static Folder GetParent(int id)
        {
            CheckInitialized();

            Folder temp = LocalRealm.Find <Folder>(id);

            if (temp.ParentId == 0)
            {
                return(null);
            }
            else
            {
                temp = LocalRealm.Find <Folder>(temp.ParentId);
                return(temp);
            }
        }
示例#17
0
        protected override void Populate(BeatmapSetInfo beatmapSet, ArchiveReader?archive, Realm realm, CancellationToken cancellationToken = default)
        {
            if (archive != null)
            {
                beatmapSet.Beatmaps.AddRange(createBeatmapDifficulties(beatmapSet.Files, realm));
            }

            foreach (BeatmapInfo b in beatmapSet.Beatmaps)
            {
                b.BeatmapSet = beatmapSet;

                // ensure we aren't trying to add a new ruleset to the database
                // this can happen in tests, mostly
                if (!b.Ruleset.IsManaged)
                {
                    b.Ruleset = realm.Find <RulesetInfo>(b.Ruleset.ShortName) ?? throw new ArgumentNullException(nameof(b.Ruleset));
                }
            }

            validateOnlineIds(beatmapSet, realm);

            bool hadOnlineIDs = beatmapSet.Beatmaps.Any(b => b.OnlineID > 0);

            onlineLookupQueue?.Update(beatmapSet);

            // ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID.
            if (hadOnlineIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineID > 0))
            {
                if (beatmapSet.OnlineID > 0)
                {
                    beatmapSet.OnlineID = -1;
                    LogForModel(beatmapSet, "Disassociating beatmap set ID due to loss of all beatmap IDs");
                }
            }
        }
        public TeamDetailsViewModel(string teamId)
        {
            _teamId = teamId;

            Realm context = Realm.GetInstance();

            var team = context.Find <Team>(teamId);

            // Using LINQ
            // var team = from t in context.All<Team>() where t.TeamId == teamId select t;
            // var team2 = context.All<Team>().Where(t => t.TeamId == teamId).FirstOrDefault();

            // Setting property values from team object
            // that we get from database
            Title       = team.Title;
            City        = team.City;
            StadiumName = team.StadiumName;
            Manager     = team.Manager;

            // You can not do like this:
            // Players = new ObservableCollection<Player>(context.All<Player>().Where(p => p.Team.TeamId == _teamId));

            // Querying by nested RealmObjects attributes is not currently supported:
            Players = new ObservableCollection <Player>(context.All <Player>().Where(p => p.Team == team));

            // Commands for toolbar items
            AddPlayerCommand  = new Command(async() => await Application.Current.MainPage.Navigation.PushAsync(new AddPlayerPage(team.TeamId)));
            EditTeamCommand   = new Command(async() => await Application.Current.MainPage.Navigation.PushAsync(new EditTeamPage(team.TeamId)));
            DeleteTeamCommand = new Command(DeleteTeam);
        }
 public void RemoveFromDB(string entityName, string vehicleId)
 {
     realmDatabase.Write(() =>
     {
         realmDatabase.Remove(realmDatabase.Find(entityName, vehicleId));
     });
 }
        public CryptoCurrencyReminderDto GetReminderDetails(CryptoCurrencyReminderDto reminder)
        {
            CryptoCurrencyReminderDto cryptoCurrencyReminder = null;

            try
            {
                _realm = Realm.GetInstance(_realmConfiguration);

                var reminderRealm = _realm.Find <CryptoCurrencyReminderRealm>(reminder.Id);

                if (reminderRealm != null)
                {
                    cryptoCurrencyReminder = new CryptoCurrencyReminderDto
                    {
                        Id         = reminderRealm.Id,
                        MarketName = reminderRealm.MarketName,
                        LowerLimit = reminderRealm.LowerLimit,
                        UpperLimit = reminderRealm.UpperLimit,
                        ExactValue = reminderRealm.ExactValue,
                    };
                }
            }
            catch (Exception ex)
            {
            }

            return(cryptoCurrencyReminder);
        }
 public void Delete(string id)
 {
     _instance.Write(() =>
     {
         _instance.Remove(_instance.Find <RealmContact>(id));
     });
 }
        public Database.Message Execute(string primaryKey)
        {
            var message = realm.Find <Database.Message>(primaryKey);

            MarkAsRead(message);
            return(message);
        }
示例#23
0
        public void SetEntry(string entryId)
        {
            if (!string.IsNullOrEmpty(entryId))
            {
                Entry = _realm.Find <VocabEntry>(entryId);
            }

            if (Entry == null)
            {
                Entry = new VocabEntry
                {
                    Metadata = new EntryMetadata
                    {
                        Date = DateTimeOffset.Now
                    }
                };

                _realm.Write(() => {
                    _realm.Add(Entry);
                });
            }

            if (Entry.Translations == null || Entry.Translations.Count == 0)
            {
                AddTranslation();
            }

            var q = from e in Entry.Translations
                    select new TranslationViewModel(e);

            Translations = q.ToList();
        }
 static RealmObject FindByPKDynamic(Realm realm, Type type, object primaryKeyValue, bool isIntegerPK)
 {
     if (isIntegerPK)
     {
         long?castPKValue;
         if (primaryKeyValue == null)
         {
             castPKValue = null;
         }
         else
         {
             castPKValue = Convert.ToInt64(primaryKeyValue);
         }
         return(realm.Find(type.Name, (long)castPKValue));
     }
     return(realm.Find(type.Name, (string)primaryKeyValue));
 }
 public T Find(string Id)
 {
     using (Realm instance = Realm.GetInstance((RealmConfigurationBase)this._realmConfiguration))
     {
         V v = (V)instance.Find <V>(Id);
         return((object)v != null?this._mapper.From(v) : default(T));
     }
 }
示例#26
0
 public string this[string fieldName]
 {
     get
     {
         int f = Realm.Find <FieldInfo>(fieldName).Index;
         return(Values[f]);
     }
 }
示例#27
0
        public override void OnReceive(Context context, Intent intent)
        {
            base.OnReceive(context, intent);

            string action = intent.Action;

            if (action == null)
            {
                return;
            }

            int appWidgetId = intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);

            if (appWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                return;
            }

            Realm             realm             = Realm.GetInstance(DB.RealmConfiguration);
            WidgetLargeParams widgetLargeParams = realm.Find <WidgetLargeParams>(appWidgetId);

            if (action.Equals(NextClick))
            {
                // Next
                int bookId    = widgetLargeParams.Book;
                int bookCount = realm.All <Book>().Count();
                realm.Write(() => widgetLargeParams.Book = bookId + 1 >= bookCount ? 0 : bookId + 1);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(PreviousClick))
            {
                // Previous
                int bookId    = widgetLargeParams.Book;
                int bookCount = realm.All <Book>().Count();
                realm.Write(() => widgetLargeParams.Book = bookId - 1 < 0 ? bookCount - 1 : bookId - 1);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(ReverseClick))
            {
                // Reverse order
                realm.Write(() => widgetLargeParams.Descending = !widgetLargeParams.Descending);
                Redraw(context, appWidgetId);
            }
            if (action.Equals(RefreshClick))
            {
                // Refresh
                Update(context, appWidgetId);
            }
            if (action.Equals(BookClick))
            {
                // Open Book Url
                string url     = Realm.GetInstance(DB.RealmConfiguration).Find <Book>(widgetLargeParams.Book).URL;
                Uri    uri     = Uri.Parse(url);
                Intent browser = new Intent(Intent.ActionView, uri);
                context.StartActivity(browser);
            }
            realm.Dispose();
        }
示例#28
0
 private void Awake()
 {
     realm    = Realm.GetInstance();
     resource = realm.Find <Resource>(resourceType.ToString());
     if (resource == null)
     {
         throw new System.Exception("Game not correctly initialised.");
     }
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.AdminAddCars);
            string user = Intent.GetStringExtra("UserProfile");

            CarName                 = FindViewById <EditText>(Resource.Id.AdminCarModelNameId);
            CarDoors                = FindViewById <EditText>(Resource.Id.AdminCarDoorsId);
            CarMileage              = FindViewById <EditText>(Resource.Id.AdminCarMileage);
            CarImage                = FindViewById <EditText>(Resource.Id.AdminCarImageId);
            mySpinner               = FindViewById <Spinner>(Resource.Id.AdminCarTypeId);
            CarNums                 = FindViewById <EditText>(Resource.Id.AdminNumberOfCarsId);
            adminAdd                = FindViewById <Button>(Resource.Id.AddId);
            adminDelete             = FindViewById <Button>(Resource.Id.DeleteId);
            myAdapter               = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, CarType);
            mySpinner.Adapter       = myAdapter;
            mySpinner.ItemSelected += spinnerClicked;

            realmObj        = Realm.GetInstance();
            adminAdd.Click += delegate
            {
                var car = new Cars();
                car.CarModelName = CarName.Text;
                car.CarDoors     = "No of Doors : " + CarDoors.Text;
                car.CarMileage   = "Mileage : " + CarMileage.Text + "/100km";
                car.CarImageId   = (int)typeof(Resource.Drawable).GetField(CarImage.Text).GetValue(null);
                car.NumberOfCars = Convert.ToInt32(CarNums.Text);
                car.CarType      = carValue;
                realmObj.Write(() =>
                {
                    realmObj.Add(car, update: true);
                });
                Intent newScreen = new Intent(this, typeof(Main_Page));
                newScreen.PutExtra("ADMIN", "admin");
                StartActivity(newScreen);
            };

            adminDelete.Click += delegate
            {
                var carInfo = realmObj.All <Cars>();
                foreach (var temp in carInfo)
                {
                    if (temp.CarModelName.Equals(CarName.Text))
                    {
                        var car      = new Cars();
                        var ModelCar = realmObj.Find <Cars>(temp.CarModelName);
                        realmObj.Write(() =>
                        {
                            realmObj.Remove(ModelCar);
                        });
                        Intent newScreen = new Intent(this, typeof(Main_Page));
                        newScreen.PutExtra("ADMIN", "admin");
                        StartActivity(newScreen);
                    }
                }
            };
        }
示例#30
0
 private void Awake()
 {
     realm   = Realm.GetInstance();
     workers = realm.Find <Unit>(Unit.Type.Worker.ToString());
     if (workers == null)
     {
         throw new System.Exception("Game not correctly initialised.");
     }
 }
示例#31
0
        private static void AddDummyData(Realm realm)
        {
            for (var i = 0; i < 1000; i++)
            {
                realm.Write(() =>
                {
                    realm.Add(new IntPrimaryKeyWithValueObject
                    {
                        Id = i,
                        StringValue = "Super secret product " + i
                    });
                });
            }

            for (var i = 0; i < 500; i++)
            {
                realm.Write(() =>
                {
                    var item = realm.Find<IntPrimaryKeyWithValueObject>(2 * i);
                    realm.Remove(item);
                });
            }
        }