コード例 #1
0
        public void SetUp()
        {
            Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration);
            realm = Realm.GetInstance();

            // we don't keep any variables pointing to these as they are all added to Realm
            using (var trans = realm.BeginWrite())
            {
                var o1 = realm.Add(new Owner { Name = "Tim" });

                var d1 = realm.Add(new Dog
                {
                    Name = "Bilbo Fleabaggins",
                    Color = "Black"
                });

                o1.TopDog = d1;  // set a one-one relationship
                o1.Dogs.Add(d1);

                var d2 = realm.Add(new Dog
                {
                    Name = "Earl Yippington III",
                    Color = "White"
                });

                o1.Dogs.Add(d2);

                // lonely people and dogs
                realm.Add(new Owner
                {
                    Name = "Dani" // the dog-less
                });

                realm.Add(new Dog // will remain unassigned
                {
                    Name = "Maggie Mongrel",
                    Color = "Grey"
                });

                trans.Commit();
            }
        }
コード例 #2
0
        private void ClickedTop(object sender, EventArgs e)
        {
            Brand.Text = "Выбранный бренд: " + ((Button)sender).Text;

            var config = new RealmConfiguration()
            {
                SchemaVersion = 1
            };
            Realm _realm    = Realm.GetInstance(config);
            var   AllMemory = _realm.All <Memory>().ToList();

            if (AllMemory.Count != 0)
            {
                var NewMemory = AllMemory[0];
                _realm.Write(() => _realm.Remove(NewMemory));
            }

            _realm.Write(() => _realm.Add(new Memory {
                SigaretBrand = ((Button)sender).Text
            }));

            DisplayAlert("", "Бренд сигарет изменён!", "ОK");
        }
コード例 #3
0
ファイル: ScreenOne.cs プロジェクト: deepanshusodhi/groupF
        private void changeUserInfo(object sender, EventArgs e)
        {
            changeName = name.Text;

            changePhone = phonenumber.Text;

            changeAge = age.Text;

            UserInfoDB saveUserData = new UserInfoDB();

            saveUserData.nameofuser = changeName;


            var toast = Toast.MakeText(context, "DATA SAVED", ToastLength.Short);

            toast.Show();

            realmDB.Write(() =>
            {
                realmDB.Add(saveUserData);
            });
            name.Text = changeName; //ISSUE FIXEDD
        }
コード例 #4
0
ファイル: MainActivity.cs プロジェクト: Bybeez/todoApp
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (resultCode == Result.Ok)
            {
                Log.Debug("log", data.ToString());

                toDos.Add(new ToDo {
                    Name        = data.Extras.GetString("name"),
                    Description = data.Extras.GetString("description"),
                    Priority    = data.Extras.GetInt("priority"),
                });
                realm.Write(() =>
                {
                    realm.Add(new ToDo {
                        Name        = data.Extras.GetString("name"),
                        Description = data.Extras.GetString("description"),
                        Priority    = data.Extras.GetInt("priority"),
                    });
                });
                adapter.NotifyDataSetChanged();
            }
        }
コード例 #5
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);
                });
            }
        }
コード例 #6
0
        //public (string First, string Last) GetName(int index)
        //{
        //    var first = "Marco";
        //    var last = "Seraphin";

        //    return (first, last);
        //}

        /// <summary>
        /// Saves the DB Value.
        /// </summary>
        /// <returns><c>true</c>, if DB Value was saved, <c>false</c> otherwise.</returns>
        /// <param name="key">Key.</param>
        /// <param name="value">Value.</param>
        public bool SaveDBValue(string key, string value)
        {
            try
            {
                realmDB.Write(() =>
                {
                    //DBSettingsObjekt settingsObject = realmDB.CreateObject("DBSettingsObjekt"); // <DBSettingsObjekt>();
                    //settingsObject.Key = key;
                    //settingsObject.Value = value;

                    DBSettingsObjekt settingsObject = new DBSettingsObjekt();
                    settingsObject.Key   = key;
                    settingsObject.Value = value;
                    realmDB.Add(settingsObject);
                });

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #7
0
        public static async void SetupRealm()
        {
            var user = await User.LoginAsync(Credentials.UsernamePassword("realm-admin", "bachelor", false), new Uri($"http://13.59.205.12:9080"));

            SyncConfiguration config = new SyncConfiguration(user, new Uri($"realm://13.59.205.12:9080/data/admins"));

            _realm = Realm.GetInstance(config);

            _realm.Write(() =>
            {
                _realm.RemoveAll();
            });

            _realm.Write(() =>
            {
                _realm.Add(new AdminModel {
                    UserId = "101126692085505836102"
                });
            });


            Console.WriteLine("Done");
        }
コード例 #8
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);
                });
            }
        }
コード例 #9
0
        private void insertDefaults(Realm realm, List <RealmKeyBinding> existingBindings, IEnumerable <IKeyBinding> defaults, string?rulesetName = null, int?variant = null)
        {
            // compare counts in database vs defaults for each action type.
            foreach (var defaultsForAction in defaults.GroupBy(k => k.Action))
            {
                // avoid performing redundant queries when the database is empty and needs to be re-filled.
                int existingCount = existingBindings.Count(k => k.RulesetName == rulesetName && k.Variant == variant && k.ActionInt == (int)defaultsForAction.Key);

                if (defaultsForAction.Count() <= existingCount)
                {
                    continue;
                }

                // insert any defaults which are missing.
                realm.Add(defaultsForAction.Skip(existingCount).Select(k => new RealmKeyBinding
                {
                    KeyCombinationString = k.KeyCombination.ToString(),
                    ActionInt            = (int)k.Action,
                    RulesetName          = rulesetName,
                    Variant = variant
                }));
            }
        }
コード例 #10
0
        private void ProcessXML(string XML, SprinterConfigs config)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(XML);
            var issues = doc.GetElementsByTagName("Issues");

            SprinterConfigs ToUpdate = new SprinterConfigs
            {
                ApiKey   = config.ApiKey,
                AppId    = config.AppId,
                AppName  = config.AppName,
                RawCache = XML
            };

            foreach (XmlNode i in issues)
            {
                var result = ConvertNode <IssuesImporter>(i);
                ToUpdate.Issues.Add(new Issues
                {
                    Browser     = result.Browser,
                    Description = result.Description,
                    Form        = result.Form,
                    FormGuide   = result.FormGuide,
                    IssueState  = result.IssueState,
                    Nr          = result.Nr,
                    IssueType   = result.IssueType,
                    ScreenSize  = result.ScreenSize,
                    ShortName   = result.ShortName,
                    Url         = result.Url,
                    UserEmail   = result.UserEmail,
                    UserName    = result.UserName,
                    UserRoles   = result.UserRoles
                });
            }
            realm.Write(() => realm.Add(ToUpdate, update: true));
        }
コード例 #11
0
        private void regClicked(object sender, System.EventArgs e)
        {
            var nameValue  = fName.Text;
            var emailValue = email.Text;
            var ageValue   = age.Text;
            var phoneValue = phNo.Text;
            var pwdValue   = pwd.Text;

            if (emailValue != "" && pwdValue != "" && nameValue != "" && ageValue != "" && phoneValue != "")
            {
                var myUserModel = new UserModel();
                myUserModel.fullName = nameValue;
                myUserModel.pswd     = pwdValue;
                myUserModel.email    = emailValue;
                myUserModel.age      = ageValue;
                myUserModel.phNo     = phoneValue;
                myDB.Write(() =>
                {
                    myDB.Add(myUserModel);
                });
                Toast.MakeText(this, "Successfully Registered..", ToastLength.Short).Show();
                Intent mainIntent = new Intent(this, typeof(MainActivity));
                StartActivity(mainIntent);
            }
            else
            {
                Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
                alert.SetTitle("Error");
                alert.SetMessage("Please Enter all fields");
                alert.SetPositiveButton("OK", (senderAlert, args) =>
                {
                    Toast.MakeText(this, "Insuffecient data", ToastLength.Short).Show();
                });
                Dialog dialog = alert.Create();
                dialog.Show();
            }
        }
コード例 #12
0
        public LoginViewModel()
        {
            LoginCommand       = new Command(Login, () => !IsBusy);
            LoginWithADCommand = new Command(LoginWithAD, () => !IsBusy);

            var cacheConfig = new RealmConfiguration("logincache.realm")
            {
                ObjectClasses = new[] { typeof(LoginDetails) }
            };

            _realm = Realm.GetInstance(cacheConfig);
            var loginDetails = _realm.All <LoginDetails>().FirstOrDefault();

            if (loginDetails == null)
            {
                using (var trans = _realm.BeginWrite())
                {
                    loginDetails = new LoginDetails
                    {
                        ServerUrl = Constants.Server.SyncHost
                    };

                    _realm.Add(loginDetails);
                    trans.Commit();
                }


                //loginDetails = new LoginDetails
                //{
                //    ServerUrl = Constants.Server.SyncHost
                //};

                //_realm.Write(() => _realm.Add(loginDetails));
            }

            Details = loginDetails;
        }
コード例 #13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            myRealm = Realm.GetInstance();
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Register);
            var myspinner = FindViewById <Spinner>(Resource.Id.spinner1);
            var myadapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, myarray);

            myadapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            myspinner.Adapter = myadapter;

            //get the contents of the fields
            firstname   = FindViewById <EditText>(Resource.Id.firstName_text);
            lastname    = FindViewById <EditText>(Resource.Id.lastName_text);
            email       = FindViewById <EditText>(Resource.Id.email_text);
            password    = FindViewById <EditText>(Resource.Id.password_text);
            profile     = FindViewById <Spinner>(Resource.Id.spinner1);
            registerBtn = FindViewById <Button>(Resource.Id.registerBtn);

            registerBtn.Click += delegate {
                var userModelOBj = new UserModel();
                userModelOBj.firstName = firstname.Text;
                userModelOBj.lastName  = lastname.Text;
                userModelOBj.email     = email.Text;
                userModelOBj.password  = password.Text;
                userModelOBj.profile   = profile.SelectedItem.ToString();

                myRealm.Write(() => {
                    myRealm.Add(userModelOBj);
                });

                var goToLogin = new Intent(this, typeof(Login));

                StartActivity(goToLogin);
            };
        }
コード例 #14
0
ファイル: TaskPage.xaml.cs プロジェクト: woodsjm/docs-realm
        async void Button_Clicked(object sender, EventArgs e)
        {
            string result = await DisplayPromptAsync("New Task", "Enter the Task Name");

            if (result == null)
            {
                return;
            }

            if (taskRealm == null)
            {
                var syncConfig = new SyncConfiguration(projectPartition, App.RealmApp.CurrentUser);
                taskRealm = await Realm.GetInstanceAsync(syncConfig);
            }

            // :code-block-start:new-task
            // :state-start: final
            var newTask = new Task()
            {
                Name      = result,
                Partition = projectPartition,
                Status    = Task.TaskStatus.Open.ToString()
            };

            taskRealm.Write(() =>
            {
                taskRealm.Add(newTask);
            });
            // :state-end: :state-uncomment-start: start
            //// TODO: create a new Task, setting the name to "result" and
            //// the status to "Open" (using the TaskStatus enum).
            //// Then add the task to the taskRealm within a transaction.
            // :state-uncomment-end:
            // :code-block-end:

            MyTasks.Add(newTask);
        }
コード例 #15
0
 public void Insert(List <LinesModel> models)
 {
     try
     {
         //using (var trans = _realm.BeginWrite())
         {
             _realm.Write(() =>
             {
                 foreach (LinesModel model in models)
                 {
                     LinesRealmModel realmModel = new LinesRealmModel();
                     realmModel.Linea           = model.Linea;
                     realmModel.IDLinea         = model.IDLinea;
                     _realm.Add(realmModel);
                 }
             });
             //trans.Commit();
         };
     }
     catch (Exception pException)
     {
         System.Diagnostics.Debug.WriteLine("Error LinesDataLayerRealm->Insert " + pException.Message);
     }
 }
コード例 #16
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Register);

            Fname    = FindViewById <EditText>(Resource.Id.FirstNameId);
            Lname    = FindViewById <EditText>(Resource.Id.LastNameId);
            Email    = FindViewById <EditText>(Resource.Id.EmailId);
            Username = FindViewById <EditText>(Resource.Id.UsernameId);
            Password = FindViewById <EditText>(Resource.Id.PasswordId);
            register = FindViewById <Button>(Resource.Id.RegisterId);

            realmObj = Realm.GetInstance();

            register.Click += delegate
            {
                var userInfo = new User();
                userInfo.FirstName = Fname.Text;
                userInfo.LastName  = Lname.Text;
                userInfo.Email     = Email.Text;
                userInfo.Username  = Username.Text;
                userInfo.Password  = Password.Text;

                realmObj.Write(() =>
                {
                    realmObj.Add(userInfo, update: true);
                });
                AlertDialog.Builder Dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = Dialog.Create();
                alert.SetMessage("Successfully Registered!!");
                alert.SetButton("OK", (c, ev) => { });
                alert.Show();
                Intent newScreen = new Intent(this, typeof(Login));
                StartActivity(newScreen);
            };
        }
コード例 #17
0
        public LoginViewModel()
        {
            LoginCommand = new Command(Login, () => !IsBusy);

            var cacheConfig = new RealmConfiguration("logincache.realm")
            {
                ObjectClasses = new[] { typeof(LoginDetails) }
            };

            _realm = Realm.GetInstance(cacheConfig);
            var loginDetails = _realm.All <LoginDetails>().FirstOrDefault();

            if (loginDetails == null)
            {
                loginDetails = new LoginDetails
                {
                    ServerUrl = Constants.RosUrl
                };

                _realm.Write(() => _realm.Add(loginDetails));
            }

            Details = loginDetails;
        }
コード例 #18
0
        public MainPage()
        {
            this.InitializeComponent();

            try
            {
                realm = Realm.GetInstance(new RealmConfiguration {
                    ShouldDeleteIfMigrationNeeded = true
                });
                ViewModel = realm.All <MainViewModel>().FirstOrDefault();
                if (ViewModel == default(MainViewModel))
                {
                    realm.Write(() =>
                    {
                        ViewModel = new MainViewModel();
                        realm.Add(ViewModel);
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
コード例 #19
0
        /// <summary>
        /// Saves a question to the database
        /// </summary>
        /// <param name="question">the question to save</param>
        private void SaveQuestion(Question question)
        {
            Realm  realmDB      = Realm.GetInstance(App.realmConfiguration(this.dbPath));
            string dbPrimaryKey = Guid.NewGuid().ToString(); // Once created, it will be PERMANENT AND IMMUTABLE

            question.QuestionId = dbPrimaryKey;

            if (question.NeedsPicture)
            {
                byte[] imageByteArray = File.ReadAllBytes(question.ImagePath);

                if (!question.ImagePath.Contains(".jpg") ||
                    !question.ImagePath.Contains(".jpeg") ||
                    !question.ImagePath.Contains(".jpe") ||
                    !question.ImagePath.Contains(".jif") ||
                    !question.ImagePath.Contains(".jfif") ||
                    !question.ImagePath.Contains(".jfi"))
                {
                    Stream       imageStream       = DependencyService.Get <IGetImage>().GetJPGStreamFromByteArray(imageByteArray);
                    MemoryStream imageMemoryStream = new MemoryStream();

                    imageStream.Position = 0;
                    imageStream.CopyTo(imageMemoryStream);

                    imageMemoryStream.Position = 0;
                    imageByteArray             = new byte[imageMemoryStream.Length];
                    imageMemoryStream.ToArray().CopyTo(imageByteArray, 0);
                }
                File.WriteAllBytes(this.DBFolderPath + "/" + dbPrimaryKey + ".jpg", imageByteArray);
            }

            realmDB.Write(() =>
            {
                realmDB.Add(question);
            });
        }
コード例 #20
0
        /// <summary>
        /// Create a new quizinfo and adds it to the Quiz DB.
        /// A copy is stored in the device quiz roster.
        /// </summary>
        /// <param name="authorName">Author</param>
        /// <param name="quizName">Quiz name</param>
        /// <param name="category">Category</param>
        public void NewQuizInfo(string authorName, string quizName, string category)
        {
            QuizInfo newQuizInfo = new QuizInfo(authorName, quizName, category)
            {
                // Sync status is irrelevant in a Quiz Database's copy of the QuizInfo
                SyncStatus = -1
            };

            this.QuizInfo = newQuizInfo;

            Realm realmDB = Realm.GetInstance(App.realmConfiguration(this.dbPath));

            realmDB.Write(() =>
            {
                realmDB.Add(newQuizInfo);
            });

            QuizInfo rosterCopy = new QuizInfo(newQuizInfo)
            {
                SyncStatus = (int)SyncStatusEnum.NeedUpload // Default to 1, meaning "needs upload" in roster
            };

            QuizRosterDatabase.SaveQuizInfo(rosterCopy);
        }
コード例 #21
0
        private void btnAdd_Clicked(object sender, EventArgs e)
        {
            var students     = realmDB.All <Student>().ToList();
            var maxStudentId = 0;

            if (students.Count != 0)
            {
                maxStudentId = students.Max(s => s.StudentID);
            }
            Student student = new Student()
            {
                StudentID   = maxStudentId + 1,
                StudentName = txtStudentName.Text
            };

            realmDB.Write(() =>
            {
                realmDB.Add(student);
            });
            txtStudentName.Text = string.Empty;
            List <Student> studentList = realmDB.All <Student>().ToList();

            listStudent.ItemsSource = studentList;
        }
コード例 #22
0
 public void AddOrUpdate(IEnumerable <T> items)
 {
     if (items == null)
     {
         return;
     }
     using (Realm realmInstance = Realm.GetInstance((RealmConfigurationBase)this._realmConfiguration))
     {
         try
         {
             realmInstance.Write((Action)(() =>
             {
                 foreach (T obj in items)
                 {
                     realmInstance.Add <V>((M0)this._mapper.To(obj), true);
                 }
             }));
         }
         catch (Exception ex)
         {
             CrossMobileAnalytics.Current.TrackException(ex, (IDictionary <string, string>)null, nameof(AddOrUpdate), "/Users/admin/myagent/macMiniBlack3/_work/2/s/eKreta.Mobile/eKreta.Mobile.Core.Standard/Repository/RealmRepository/BaseRealmRepository.cs", 66);
         }
     }
 }
コード例 #23
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     masterRealmInstance = Realm.GetInstance("RecyclerViewExample.realm");
     if (masterRealmInstance.All <ARealmObject>().Count() == 0)
     {
         masterRealmInstance.Write(() =>                     // Create some test data
         {
             for (int i = 0; i < 10000; i++)
             {
                 masterRealmInstance.Add(new ARealmObject {
                     Key = i, Caption = $"StackOverFlow # + {i.ToString()}", SeekBar1 = 50, SeekBar2 = 50
                 });
             }
         });
     }
     SetContentView(Resource.Layout.ARecyclerLayOut);
     recyclerView = (RecyclerView)FindViewById(Resource.Id.recyclerView);
     recyclerView.HasFixedSize = true;
     layoutManager             = new LinearLayoutManager(this);
     recyclerView.SetLayoutManager(layoutManager);
     adapter = new RealmAdapter((RealmConfiguration)masterRealmInstance.Config);
     recyclerView.SetAdapter(adapter);
 }
コード例 #24
0
ファイル: DataStore.cs プロジェクト: robertmiles3/realmcrash2
 public void Seed()
 {
     _realm.Write(() =>
     {
         for (var i = 0; i < 10; i++)
         {
             var folder = new Folder
             {
                 Id    = Guid.NewGuid().ToString("N"),
                 Title = $"Folder {i + 1}",
             };
             for (int j = 0; j < 10; j++)
             {
                 var item = new Item
                 {
                     Id    = Guid.NewGuid().ToString("N"),
                     Title = $"Item {j + 1}",
                 };
                 folder.Items.Add(item);
             }
             _realm.Add(folder);
         }
     });
 }
コード例 #25
0
ファイル: BaseModel.cs プロジェクト: ivNetAdmin/iDigIt
        internal void AddJobToNextSeason(Job job)
        {
            var firstYear  = Convert.ToInt16(job.Date.Year + 1);
            var secondYear = Convert.ToInt16(job.Date.Year + 2);

            _realmInstance.Write(() =>
            {
                var newJob = new Job
                {
                    Name  = job.Name,
                    Plant = job.Plant,
                    Type  = job.Type,
                    Date  = NextSeasonDate.Date(job.Date)
                };

                newJob.JobId = string.Format("{0}{1}{2}{3}",
                                             newJob.Name,
                                             newJob.Plant,
                                             newJob.Type,
                                             newJob.Date.ToString("yyyyMMdd")).ToLower().Replace(" ", "");

                _realmInstance.Add(newJob, true); // Add the whole set of details
            });
        }
コード例 #26
0
 public void Insert(List <AreasModel> model)
 {
     try
     {
         //using (var trans = _realm.BeginWrite())
         {
             _realm.Write(() =>
             {
                 for (int i = 0; i < model.Count; i++)
                 {
                     AreasRealmModel realmModel = new AreasRealmModel();
                     realmModel.IDArea          = model[i].IDArea;
                     realmModel.Area            = model[i].Area;
                     _realm.Add(realmModel);
                 }
             });
             //trans.Commit();
         };
     }
     catch (Exception pException)
     {
         System.Diagnostics.Debug.WriteLine("Error AreasDataLayerRealm->Insert " + pException.Message);
     }
 }
コード例 #27
0
        /// <summary>
        /// Stores the timetable to the database.
        /// </summary>
        /// <param name="Semester">Semester.</param>
        /// <param name="WhichSemester">Which semester.</param>
        public Student StoreTimetableToDataBase(Dictionary <string, List <Subject> > Semester, int WhichSemester, Student Student)
        {
            var check = db.All <Student>().ToList();

            db.Write(() =>
            {
                if (Student.WeekSemester1.Count == 0)
                {
                    db.RemoveAll();
                }

                //check if there is an exising timetable if yea delete it but before deleting
                //	 if (check.Count() > 1)
                {
                    //	RemoveAllLeaveOne();//dont know why imdoing this :(
                }
                int dayCounter = 0;
                foreach (var dictionary in Semester)
                {
                    string day = dictionary.Key;                     //get the day we currently looking at i.e Monday
                    dayCounter++;
                    Day temp = new Day();

                    temp.day = day;
                    for (int i = 0; i < dictionary.Value.Count; i++)
                    {
                        temp.Subjects.Add(dictionary.Value.ToList()[i]);
                    }
                    temp.Semester = WhichSemester;
                    if (WhichSemester == 1)
                    {
                        Student.WeekSemester1.Add(temp);
                    }
                    else
                    {
                        Student.WeekSemester2.Add(temp);
                    }
                }
                db.Add(Student, true);
            });
            db.Refresh();
            return(Student);
        }
コード例 #28
0
 //agregar objeto a la base
 public void addItem(Allergies o)
 {
     realm.Write(() => {
         realm.Add(o);
     });
 }
コード例 #29
0
 public void Write()
 {
     realm.Write(() => {
         realm.Add(this, true);
     });
 }
コード例 #30
0
ファイル: App.xaml.cs プロジェクト: AlexIzzy/CVPRTest
 protected override void OnStart()
 {
     _realm = RealmHelper.GetRealm();
     _realm.Write(() =>
     {
         _realm.RemoveAll();
     });
     _realm.Write(() =>
     {
         var speaker1 = new Visitor
         {
             Id       = Guid.NewGuid().ToString(),
             Name     = "Visitor1",
             Email    = "*****@*****.**",
             Password = "******"
         };
         _realm.Add(speaker1);
         var speaker2 = new Visitor
         {
             Id       = Guid.NewGuid().ToString(),
             Name     = "Visitor2",
             Email    = "*****@*****.**",
             Password = "******"
         };
         _realm.Add(speaker2);
         var speaker3 = _realm.Add(new Visitor
         {
             Id       = Guid.NewGuid().ToString(),
             Name     = "Visitor3",
             Email    = "*****@*****.**",
             Password = "******"
         });
         var message1 = _realm.Add(new Message
         {
             ID = Guid.NewGuid().ToString(),
             MessageDateTime = new DateTimeOffset(DateTime.Parse("12:30")),
             MessageText     = "Test message 1",
             Sender          = speaker1,
             Reciever        = speaker2
         });
         var message2 = _realm.Add(new Message
         {
             ID = Guid.NewGuid().ToString(),
             MessageDateTime = new DateTimeOffset(DateTime.Parse("13:30")),
             MessageText     = "Test message 2",
             Sender          = speaker2,
             Reciever        = speaker3
         });
         var message3 = _realm.Add(new Message
         {
             ID = Guid.NewGuid().ToString(),
             MessageDateTime = new DateTimeOffset(DateTime.Parse("11:30")),
             MessageText     = "Test message 3",
             Sender          = speaker3,
             Reciever        = speaker1
         });
         var myTranslation = new Translation()
         {
             Id   = Guid.NewGuid().ToString(),
             Url  = "http://edge.mixlr.com/channel/nikqs",
             Name = "Test Translation"
         };
         _realm.Add(myTranslation);
         speaker1.AddedVisitors.Add(speaker2);
         speaker1.AddedVisitors.Add(speaker3);
         speaker2.AddedVisitors.Add(speaker1);
         speaker3.AddedVisitors.Add(speaker1);
     });
     _realm.Dispose();
 }
コード例 #31
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ProfileView);

            string UserFname = Intent.GetStringExtra("FIRSTNAME");
            string UserLname = Intent.GetStringExtra("LASTNAME");
            string UserEmail = Intent.GetStringExtra("USERID");

            ProfileFname    = FindViewById <TextView>(Resource.Id.ProfileFirstNameId);
            ProfileLname    = FindViewById <TextView>(Resource.Id.ProfileLastNameId);
            ProfileEmail    = FindViewById <TextView>(Resource.Id.ProfileEmailId);
            ProfileUsername = FindViewById <TextView>(Resource.Id.ProfileUsernameId);
            ProfilePassword = FindViewById <TextView>(Resource.Id.ProfilePasswordId);
            Update          = FindViewById <Button>(Resource.Id.UpdateId);
            back            = FindViewById <Button>(Resource.Id.BackId);

            realmObj = Realm.GetInstance();
            var userInfo = realmObj.All <User>();

            foreach (var temp in userInfo)
            {
                if (temp.Email.Equals(UserEmail))
                {
                    ProfileFname.Text    = temp.FirstName.ToString();
                    ProfileLname.Text    = temp.LastName.ToString();
                    ProfileEmail.Text    = temp.Email.ToString();
                    ProfileUsername.Text = temp.Username.ToString();
                    ProfilePassword.Text = temp.Password.ToString();
                }
            }
            Update.Click += delegate
            {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);

                LayoutInflater layoutInflate = LayoutInflater.From(this);
                View           view          = layoutInflate.Inflate(Resource.Layout.ProfileUpdatePopUp, null);
                alertBuilder.SetView(view);
                var Fname    = view.FindViewById <TextView>(Resource.Id.PopUpFirstNameId);
                var Lname    = view.FindViewById <EditText>(Resource.Id.PopUpLastNameId);
                var email    = view.FindViewById <TextView>(Resource.Id.PopUpEmailId);
                var userName = view.FindViewById <EditText>(Resource.Id.PopUpUsernameId);
                var pass     = view.FindViewById <EditText>(Resource.Id.PopUpPasswordId);

                email.Text = UserEmail.ToString();
                Fname.Text = UserFname.ToString();

                alertBuilder.SetCancelable(false)
                .SetPositiveButton("Update", delegate
                {
                    var user = realmObj.All <User>();
                    foreach (var temp in user)
                    {
                        if (temp.Email.Equals(UserEmail))
                        {
                            var updateInfo       = new User();
                            updateInfo.FirstName = Fname.Text;
                            updateInfo.LastName  = Lname.Text;
                            updateInfo.Email     = email.Text;
                            updateInfo.Username  = userName.Text;
                            updateInfo.Password  = pass.Text;

                            realmObj.Write(() =>
                            {
                                realmObj.Add(updateInfo, update: true);
                            });
                        }
                    }
                    Intent newScreen = new Intent(this, typeof(ViewProfile));
                    newScreen.PutExtra("FIRSTNAME", UserFname);
                    newScreen.PutExtra("LASTNAME", UserLname);
                    newScreen.PutExtra("USERID", UserEmail);
                    StartActivity(newScreen);
                })
                .SetNegativeButton("Cancel", delegate
                {
                    alertBuilder.Dispose();
                });
                AlertDialog dialog = alertBuilder.Create();
                dialog.Show();
            };

            back.Click += delegate
            {
                Intent newScreen = new Intent(this, typeof(Main_Page));
                newScreen.PutExtra("FIRSTNAME", UserFname);
                newScreen.PutExtra("LASTNAME", UserLname);
                newScreen.PutExtra("EMAIL", UserEmail);
                StartActivity(newScreen);
            };
        }
コード例 #32
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            myEmail = Intent.GetStringExtra("email");
            SetContentView(Resource.Layout.AddItem);
            myDB = Realm.GetInstance(config);


            var           hotelList = from a in myDB.All <HotelModel>() where (a.hotelName != "") select a;
            List <string> listHotel = new List <string>();


            foreach (var u in hotelList)
            {
                listHotel.Add(u.hotelName);
            }

            dropDownList = listHotel.ToArray();

            edtItemName    = FindViewById <EditText>(Resource.Id.edtItemName);
            edtPrice       = FindViewById <EditText>(Resource.Id.edtPrice);
            edtDesc        = FindViewById <EditText>(Resource.Id.edtDesc);
            btnAddMenuItem = FindViewById <Button>(Resource.Id.btnAddMenuItem);


            /* Dropdown code */
            spinnerCategory = FindViewById <Spinner>(Resource.Id.spinnerHotelName);
            ArrayAdapter myDropdownAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, dropDownList);

            spinnerCategory.Adapter       = myDropdownAdapter;
            spinnerCategory.ItemSelected += mySpinnerViewIteamSelected;

            spinnerImg = FindViewById <Spinner>(Resource.Id.spinnerImage);
            ArrayAdapter myDropdownAdapter2 = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, imgDisp);

            spinnerImg.Adapter       = myDropdownAdapter2;
            spinnerImg.ItemSelected += mySpinnerViewIteamSelected2;


            btnAddMenuItem.Click += delegate
            {
                if (edtItemName.Text == "")
                {
                    msg = "Please enter Item Name";
                    Alert(msg);
                }
                else if (edtPrice.Text == "")
                {
                    msg = "Please enter Price";
                    Alert(msg);
                }
                else if (edtDesc.Text == "")
                {
                    msg = "Please enter Description";
                    Alert(msg);
                }
                else
                {
                    ItemModel objItemModel = new ItemModel();

                    int count = myDB.All <ItemModel>().Count();

                    //increatement index
                    int nextID = count + 1;

                    //insert new value
                    objItemModel.id          = nextID;
                    objItemModel.hotelId     = hotelId;
                    objItemModel.itemName    = edtItemName.Text;
                    objItemModel.price       = Convert.ToDouble(edtPrice.Text);
                    objItemModel.description = edtDesc.Text;
                    objItemModel.itemImg     = imgPath;


                    myDB.Write(() =>
                    {
                        myDB.Add(objItemModel);
                    });
                    Toast.MakeText(this, "Item Added", ToastLength.Short).Show();
                    Intent ItemIntent = new Intent(this, typeof(AddItem));
                    ItemIntent.PutExtra("email", myEmail);
                    StartActivity(ItemIntent);
                }
            };
        }