Beispiel #1
0
        internal override async System.Threading.Tasks.Task Send(IEnumerable<Task> tasks, IMobileServiceTable<Task> tasksTable,
            IEnumerable<TaskAssignedTo> taskAssignedToRelationship, IMobileServiceTable<TaskAssignedTo> taskAssignedToTable,
            Person user)
        {
            if (DeleteRelationshipOnly)
            {
                var list = await taskAssignedToTable.Where(p => p.TaskId == this.TaskId && p.PersonUserId == user.UserId).ToEnumerableAsync();
                foreach (var taskAssignedTo in list)
                    await taskAssignedToTable.DeleteAsync(taskAssignedTo);
            }
            else
            {
                var list = await taskAssignedToTable.Where(p => p.TaskId == this.TaskId).ToEnumerableAsync();
                foreach (var taskAssignedTo in list)
                    await taskAssignedToTable.DeleteAsync(taskAssignedTo);

                if (this.AzureTaskId != 0)
                {
                    await tasksTable.DeleteAsync(new Task() { Id = AzureTaskId });
                }
            }
        }
Beispiel #2
0
        public async Task ReadAsyncGeneric()
        {
            string appUrl = "http://www.test.com";
            string appKey = "secret...";

            TestServiceFilter   hijack  = new TestServiceFilter();
            MobileServiceClient service = new MobileServiceClient(appUrl, appKey)
                                          .WithFilter(hijack);

            hijack.Response.Content =
                new JsonArray()
                .Append(new JsonObject().Set("id", 12).Set("Name", "Bob"))
                .Stringify();

            IMobileServiceTable <Person> table = service.GetTable <Person>();
            List <Person> people = await table.Where(p => p.Id == 12).ToListAsync();

            Assert.AreEqual(1, people.Count);
            Assert.AreEqual(12L, people[0].Id);
            Assert.AreEqual("Bob", people[0].Name);
        }
Beispiel #3
0
        public async Task <bool> GetLogin(string a, string b)
        {
            try
            {
                //System.Diagnostics.Debug.WriteLine("Level 1");

                loginTable = Client.GetTable <LoginAgent>();

                //System.Diagnostics.Debug.WriteLine("Level 2");

                List <LoginAgent> items = await loginTable
                                          .Where(r => r.Username == a)
                                          .Where(r => r.Password == b)
                                          .ToListAsync();

                //System.Diagnostics.Debug.WriteLine("Level 3");

                items.Add(new LoginAgent()
                {
                    Password = "******", Username = "******"
                });

                if (items[0].Username.Equals(a) && items[0].Password.Equals(b))
                {
                    System.Diagnostics.Debug.WriteLine("User found: " + items[0].Username);
                    UserData.HostLink       = items[0].HostLink;
                    UserData.ConnectionCode = items[0].ConnectionCode;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            Client.Dispose();
        }
        private async void SignUpClicked(object sender, EventArgs e)
        {
            if (SignUp_Password.Text == SignUp_PassConfirm.Text)
            {
                var users = await UsersTable.Where(x => x.Email == SignUp_Email.Text).ToListAsync();

                if (users.Count == 0)
                {
                    var user = new Models.User()
                    {
                        Email      = SignUp_Email.Text,
                        Location   = SignUp_Location.Text,
                        Name       = SignUp_Name.Text,
                        Password   = SignUp_Password.Text,
                        Surname    = SignUp_Surname.Text,
                        Phone      = SignUp_Phone.Text,
                        Instrument = SignUp_Instrument.SelectedItem.ToString()
                    };

                    await UsersTable.InsertAsync(user);

                    if (user.Id != null)
                    {
                        await Navigation.PopAsync();
                    }
                    else
                    {
                        await DisplayAlert("Error", "access denied", "Cancel");  //TODO: Insert Error Alert
                    }
                }
                else
                {
                    await DisplayAlert("Error", "User exists", "Try Again"); //TODO: Exists User Error
                }
            }
            else
            {
                await DisplayAlert("Error", "Validation Error", "Cancel"); //TODO: Validation Error Alert
            }
        }
Beispiel #5
0
        async private void LoginAuthenticate()
        {
            try
            {
                //search database for username and password
                usersList = await userTable
                            .Where(Users => Users.username == loginUsername.Text && Users.password == loginPassword.Password)
                            .ToCollectionAsync();

                if (loginUsername.Text != "" || loginPassword.Password != "")
                {
                    if (usersList.Count == 0)
                    {
                        var dialog = new MessageDialog("Username/Password incorrect. Please try again.");
                        await dialog.ShowAsync();
                    }
                    else
                    {
                        var dialog = new MessageDialog("Login Successful!");
                        await dialog.ShowAsync();

                        SessionUser.sessionUserID   = "";
                        SessionUser.sessionUsername = "";
                        SessionUser.sessionUserID   = usersList[0].ID;
                        SessionUser.sessionUsername = loginUsername.Text;
                        this.Frame.Navigate(typeof(NavigationPage), null);
                    }
                }
                else
                {
                    var dialog = new MessageDialog("Please enter username and password.");
                    await dialog.ShowAsync();
                }
            }
            catch (Exception em)
            {
                var dialog = new MessageDialog("An Error Occured: " + em.Message);
                await dialog.ShowAsync();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Azure Mobile Service に接続して ToDo データを取得する
        /// </summary>
        /// <returns></returns>
        private async Task RefreshItemsFromTableAsync()
        {
            try
            {
                List <ToDo> list;
                if (setting.DispCompleted == true)
                {
                    list = await todoTable.ToListAsync();
                }
                else
                {
                    // 未完了の項目のみ取得する
                    list = await todoTable.Where(x => x.Completed == false).ToListAsync();
                }
                // 表示順を変える
                switch (setting.SortOrder)
                {
                case 0:     // 作成日順/ID順
                    list = list.OrderByDescending(x => x.CreatedAt).ToList();
                    break;

                case 1:     // 項目名順
                    list = list.OrderBy(x => x.Text).ToList();
                    break;

                case 2:     // 期日順
                    list = list.OrderBy(x => x.DueDate).ToList();
                    break;
                }

                this.viewModel.Items.Clear();
                foreach (var it in list)
                {
                    viewModel.Items.Add(it);
                }
            }
            catch (Exception ex)
            {
            }
        }
        public async Task AsyncTableOperationsWithSystemProperties()
        {
            await EnsureEmptyTableAsync <ToDoWithSystemPropertiesType>();

            IMobileServiceTable <ToDoWithSystemPropertiesType> allSystemPropertiesTable = GetClient().GetTable <ToDoWithSystemPropertiesType>();

            // Regular insert
            ToDoWithSystemPropertiesType item = new ToDoWithSystemPropertiesType()
            {
                String = "a value"
            };
            await allSystemPropertiesTable.InsertAsync(item);

            Assert.IsNotNull(item.CreatedAt);
            Assert.IsNotNull(item.UpdatedAt);
            Assert.IsNotNull(item.Version);

            // Explicit System Properties insert
            ToDoWithSystemPropertiesType item2 = new ToDoWithSystemPropertiesType();
            await allSystemPropertiesTable.InsertAsync(item2);

            Assert.IsNotNull(item2.CreatedAt);
            Assert.AreEqual(new DateTime(), item2.UpdatedAt);
            Assert.IsNotNull(item2.Version);

            // Explicit System Properties Read
            IEnumerable <ToDoWithSystemPropertiesType> results = await allSystemPropertiesTable.Where(p => p.Id == item2.Id).ToEnumerableAsync();

            ToDoWithSystemPropertiesType[] items = results.ToArray();

            Assert.AreEqual(1, items.Count());
            Assert.AreEqual(new DateTime(), items[0].CreatedAt);
            Assert.IsNotNull(items[0].UpdatedAt);
            Assert.IsNotNull(items[0].Version);

            await allSystemPropertiesTable.DeleteAsync(item);

            await allSystemPropertiesTable.DeleteAsync(item2);
        }
Beispiel #8
0
        public async Task <Wallet> GetWalletData()
        {
            Wallet wallet = null;

            //Check if wallet has enough balance
            IMobileServiceTable <Wallet> walletData = client.GetTable <Wallet>();

            //Getting the Wallet details from the Database
            List <Wallet> walletList = await walletData.Where
                                           (item => item.Email == client.CurrentUser.UserId).ToListAsync();

            if (walletList.Count == 0)
            {
                return(wallet);
            }
            else
            {
                wallet = walletList[0];

                return(wallet);
            }
        }
Beispiel #9
0
        private async void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            var toggle = sender as ToggleSwitch;

            if (toggle == null)
            {
                return;
            }
            Debug.WriteLine(String.Format("Called Toggle_switch({0})", toggle.Name));
            SetProgressRing(toggle.Name, true);
            currentHouseEntity.IsParameterBusy++;
            var forUpdate = await parameters.Where(i => i.Name == toggle.Name).ToListAsync();

            if (forUpdate.Count == 0)
            {
                Parameters fanRow = new Parameters
                {
                    Name  = toggle.Name,
                    Value = toggle.IsOn ? 1 : 0
                };
                await InsertParameters(fanRow);
            }
            else
            {
                foreach (var item in forUpdate)
                {
                    item.Value = toggle.IsOn ? 1 : 0;
                    try
                    {
                        await parameters.UpdateAsync(item);
                    }
                    catch (MobileServiceInvalidOperationException)
                    {
                    }
                }
            }
            SetProgressRing(toggle.Name, false);
            currentHouseEntity.IsParameterBusy--;
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            string id = e.Parameter as string;

            LoadingBar.Visibility      = Visibility.Visible;
            LoadingBar.IsIndeterminate = true;
            try
            {
                items3 = await Table3.Where(Diary
                                            => Diary.Id == id).ToCollectionAsync();

                string[] ids = items3[0].Tour_List.Split(',');
                foreach (string nid in ids)
                {
                    if (nid != "")
                    {
                        items2 = await Table2.Where(Tour
                                                    => Tour.Id == nid).ToCollectionAsync();

                        m       = new Purchsed();
                        m.Id    = items2[0].Id;
                        m.Title = items2[0].Title;
                        m.Image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(items2[0].Cover_Url));
                        m.Type  = "T";
                        Tlist.Add(m);
                    }
                }
                DiaryView.DataContext = Tlist;
                LoadingBar.Visibility = Visibility.Collapsed;
            }

            catch (Exception)
            {
                MessageDialog msgbox = new MessageDialog("Sorry can't update now");
                await msgbox.ShowAsync();

                LoadingBar.Visibility = Visibility.Collapsed;
            }
        }
Beispiel #11
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            LoadingBar.Visibility      = Visibility.Visible;
            LoadingBar.IsIndeterminate = true;
            try
            {
                items = await Table.Where(User
                                          => User.username == UserName.Text).ToCollectionAsync();

                if (items.Count != 0)
                {
                    if (Password.Password == items[0].password)
                    {
                        MessageDialog msgbox = new MessageDialog("Welcome " + UserName.Text);
                        await msgbox.ShowAsync();

                        StorageFolder folder     = Windows.Storage.ApplicationData.Current.LocalFolder;
                        StorageFile   sampleFile =
                            await folder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);

                        await Windows.Storage.FileIO.WriteTextAsync(sampleFile, UserName.Text);

                        Frame.Navigate(typeof(Downloads));
                    }
                }
                else
                {
                    LoadingBar.Visibility = Visibility.Collapsed;
                    MessageDialog msgbox = new MessageDialog("Password or username incorrect");
                    await msgbox.ShowAsync();
                }
            }
            catch (Exception)
            {
                LoadingBar.Visibility = Visibility.Collapsed;
                MessageDialog msgbox = new MessageDialog("Sorry Can't connect");
                await msgbox.ShowAsync();
            }
        }
        private async Task RefreshTodoItems()
        {
            MobileServiceInvalidOperationException exception = null;

            try
            {
                // This code refreshes the entries in the list view by querying the TodoItems table.
                // The query excludes completed TodoItems.

                /*
                 * items = await todoTable
                 *  .Where(todoItem => todoItem.Complete == false)
                 *  .ToCollectionAsync();
                 *
                 * natanItems = await natanTable
                 *  .Where(natanItem => natanItem.Complete == false)
                 *  .ToCollectionAsync();
                 */

                gameItems = await gameTable
                            .Where(gameItem => gameItem.Complete == false && gameItem.PlayersNum < 4 && gameItem.GameStarted == false)
                            .ToCollectionAsync();
            }
            catch (MobileServiceInvalidOperationException e)
            {
                exception = e;
            }

            if (exception != null)
            {
                await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
            }
            else
            {
                //ListItems.ItemsSource = items;
                ListItems.ItemsSource = gameItems;
                //this.ButtonSave.IsEnabled = true;
            }
        }
        private async void spremiButton(object obj)
        {
            using (var DB = new PlanBDbContext())
            {
                if (TextObaveze.Length < 3 || vidljivost == Vidljivost.Nista)
                {
                    Poruka = new MessageDialog("Unesite sve tražene podatke.");
                    await Poruka.ShowAsync();

                    return;
                }

                else
                {
                    // DateTime d = DateTime.ParseExact(DatumText, "dd.mm.yyyy.", System.Globalization.CultureInfo.InvariantCulture);
                    //new DateTime(int.Parse(String.Concat(DatumText[6] + DatumText[7] + DatumText[8] + DatumText[9])), int.Parse(String.Concat(DatumText[3] + DatumText[4])), int.Parse(String.Concat(DatumText[0] + DatumText[1])))

                    ObavezaAzure obavezaAzure = new ObavezaAzure();
                    obavezaAzure.datum     = datum;
                    obavezaAzure.kreatorID = korisnik.idAzure;
                    obavezaAzure.postaviVidljivost(vidljivost);
                    obavezaAzure.sadrzaj   = TextObaveze;
                    obavezaAzure.prioritet = int.Parse(sliderVrijednost);
                    IMobileServiceTable <ObavezaAzure> azureObaveze = App.MobileService.GetTable <ObavezaAzure>();
                    List <ObavezaAzure> listaAzure = await azureObaveze.Where(x => x.id != "").ToListAsync();

                    obavezaAzure.redniBroj = listaAzure.Count + 1;
                    await userTableObj.InsertAsync(obavezaAzure);

                    Obaveza obaveza = new Obaveza(0, datum, TextObaveze, vidljivost, int.Parse(sliderVrijednost), korisnik.idAzure);
                    obaveza.kreatorAzure = korisnik.idAzure; // M A I D DODAO
                    korisnik.Obaveze.Add(obaveza);
                    DB.Obaveze.Add(obaveza);
                    DB.SaveChanges();
                    Poruka = new MessageDialog("Uspješno pohranjena obaveza.");
                    await Poruka.ShowAsync();
                }
            }
        }
Beispiel #14
0
        public async Task <ActionResult> HandleCustomerCall(string CallSid, string From)
        {
            var response = new TwilioResponse();

            //check the caller ID and try to find a call config that matches it
            IMobileServiceTable <WarmCall> warmCallTable = MobileService.GetTable <WarmCall>();
            var warmCalls = await warmCallTable.ReadAsync <WarmCall>(warmCallTable.Where(w => w.CustomerPhone == From));

            var warmCall = warmCalls.FirstOrDefault();

            if (warmCall != null)
            {
                //update with the call sid
                warmCall.CustomerCallSid = CallSid;
                await warmCallTable.UpdateAsync(warmCall);

                //put the customer into a conference
                response.Say("Please while while we conjure a support agent");
                response.DialConference(CallSid);

                //dial an agent
                var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
                var result = client.InitiateOutboundCall("+17862200728", warmCall.AgentOnePhone, Url.ActionAbsolute("HandleAgentOneCall"));

                if (result.RestException != null)
                {
                    Console.WriteLine(result.RestException.Message);
                }
                //let the browser know that the customer has connected and we're calling the agent
            }
            else
            {
                response.Say("Who are you?  Go away!");
                response.Hangup();
            }


            return(TwiML(response));
        }
Beispiel #15
0
        public async Task <BAMAppUser> GetUserByEmail(string email)
        {
            try
            {
                List <BAMAppUser> bamAppUser = await bamAppUserTable.Where(
                    user => user.Email == email).ToListAsync();

                if (bamAppUser.Count > 0)
                {
                    return(bamAppUser[0]);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                ReportError(ex);
                return(null);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Updates the data in the expense chart with the latest expenses
        /// </summary>
        /// <returns></returns>
        private async Task RefreshExpenseChart()
        {
            // Display the progress wheel when getting data
            ProgressRing LoginProgress = new ProgressRing();

            LoginProgress.HorizontalAlignment = HorizontalAlignment.Center;
            LoginProgress.VerticalAlignment   = VerticalAlignment.Center;
            ContentRoot.Children.Add(LoginProgress);
            LoginProgress.IsActive = true;

            // Get a handle to the expense table in the database
            IMobileServiceTable <Expense> ExpenseTable = App.alltheairgeadClient.GetTable <Expense>();

            // Query the database for all the expenses after the minimum displayed date
            Expenses = await ExpenseTable.Where(a => (a.Date > MinExpenseDate) && (a.Date <= DateTime.Now)).OrderByDescending(a => a.Date).ToListAsync();

            // Update every series in the chart
            foreach (LineSeries i in ExpenseChart.Series)
            {
                List <DateValueItem> Items = new List <DateValueItem>();
                foreach (Expense j in Expenses)
                {
                    // Add expenses for the current series only
                    if (j.Category == (string)i.Title || ExpenseChart.Series.IndexOf(i) == 0)
                    {
                        Items.Add(new DateValueItem {
                            Date = (j.Date + j.Time.TimeOfDay), Value = (int)j.Price, Id = j.Id
                        });
                    }
                }

                i.ItemsSource = Items;
                i.Refresh();
            }

            // Disable the progress wheel
            LoginProgress.IsActive = false;
            ContentRoot.Children.Remove(LoginProgress);
        }
        private async void SetUpProfile()
        {
            string userName = (string)Global.GetRepositoryValue("userName");
            var    userRes  = await usertable.Where(usr => usr.Email == userName).ToEnumerableAsync();

            User user = userRes.SingleOrDefault();

            if (user != null)
            {
                await GetProfileImage(user.Email);

                FirstNameTextBlock.Text = user.Fname;
                LastNameTextBlock.Text  = user.Lname;
                EmailTextBlock.Text     = user.Email;
                MobileTextBlock.Text    = user.Mobile;
                SummaryTextBox.Text     = user.Summary;
                string serialized = JsonConvert.SerializeObject(user);
                Global.SetRepositoryValue("userProfile", serialized);

                // SummaryTextBox.T
            }
        }
Beispiel #18
0
        public async Task <User> Login(string mailadress, string password)
        {
            Init();

            try
            {
                IEnumerable <User> userdata = await userTable.Where(u => u.MailAdress == mailadress).ToEnumerableAsync();

                var           passwordsalt_fromServer = userdata.First().Password_Salt;
                var           passwordhash_fromServer = userdata.First().Password;
                SHA256Managed sha256hash            = new SHA256Managed();
                var           buff                  = System.Text.Encoding.UTF8.GetBytes(password + passwordsalt_fromServer);
                var           buffhash              = sha256hash.ComputeHash(buff);
                var           passwordhash_fromUser = "******";
                foreach (int num in buffhash)
                {
                    passwordhash_fromUser += num;
                }
                if (passwordhash_fromServer == passwordhash_fromUser)
                {
                    return(userdata.FirstOrDefault());
                }
                else
                {
                    return(null);
                }
            }
            catch (MobileServiceInvalidOperationException msioe)
            {
                Debug.WriteLine("Invalid sync operation: {0}", new[] { msioe.Message });
                return(null);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Sync error: {0}", new[] { e.Message });
                return(null);
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            rec = new StoreListing();
            LoadingBar.Visibility      = Visibility.Visible;
            LoadingBar.IsIndeterminate = true;
            rec           = e.Parameter as StoreListing;
            Title.Text    = rec.Title;
            Cover.Source  = rec.Image;
            FullCost.Text = "Diary " + rec.Price;
            string[] ids = rec.MyId.Split(',');
            try
            {
                foreach (string nid in ids)
                {
                    if (nid != "")
                    {
                        recM  = new StoreListing();
                        items = await Table.Where(Tour
                                                  => Tour.Id == nid).ToCollectionAsync();

                        recM.Id    = items[0].Id;
                        recM.Title = items[0].Title;
                        recM.MyId  = items[0].Scrap_List;
                        recM.Image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(items[0].Cover_Url)); // image fromasset store
                        sl.Add(recM);
                    }
                }
                StoreListView.DataContext = sl;
                LoadingBar.Visibility     = Visibility.Collapsed;
            }
            catch (Exception)
            {
                MessageDialog msgbox = new MessageDialog("Sorry can't update now");
                await msgbox.ShowAsync();

                LoadingBar.Visibility = Visibility.Collapsed;
            }
        }
Beispiel #20
0
        public static async Task <List <Journeys> > SearchJourneys(Search search)
        {
            LatLng maxFrom = LocationHelper.getMaxLatLng(new LatLng(search.FromLat, search.FromLon), search.Range);
            LatLng minFrom = LocationHelper.getMinLatLng(new LatLng(search.FromLat, search.FromLon), search.Range);
            LatLng maxTo   = LocationHelper.getMaxLatLng(new LatLng(search.ToLat, search.ToLon), search.Range);
            LatLng minTo   = LocationHelper.getMinLatLng(new LatLng(search.ToLat, search.ToLon), search.Range);

            CurrentPlatform.Init();
            IMobileServiceTable <Journeys> mTable = MobileService.GetTable <Journeys>();
            List <Journeys> items = await mTable
                                    .Where(x => x.FromLat <= maxFrom.Latitude && x.FromLon <= maxFrom.Longitude &&
                                           x.FromLat >= minFrom.Latitude && x.FromLon >= minFrom.Longitude &&
                                           x.ToLat <= maxTo.Latitude && x.ToLon <= maxTo.Longitude &&
                                           x.ToLat >= minTo.Latitude && x.ToLon >= minTo.Longitude &&
                                           x.Completed == false && x.Filled == false)
                                    .ToListAsync();

            if (items.Count > 0)
            {
                List <Journeys> result  = new List <Journeys>();
                DateTime        depDate = DateTime.Parse(search.DepartureDate);
                DateTime        minTime = DateTime.Parse(search.MinDepartureDateTime);
                DateTime        maxTime = DateTime.Parse(search.MaxDepartureDateTime);
                foreach (Journeys j in items)
                {
                    DateTime dep = DateTime.Parse(j.DepartureDate);
                    if (dep == depDate && minTime <= DateTime.Parse(j.DepartureDateTime) && maxTime >= DateTime.Parse(j.DepartureDateTime))
                    {
                        result.Add(j);
                    }
                }
                return(result);
            }
            else
            {
                return(new List <Journeys>());
            }
        }
        public async Task FilterReadAsyncWithEmptyStringIdAgainstStringIdTable()
        {
            await EnsureEmptyTableAsync <ToDoWithStringId>();

            string[] testIdData = IdTestData.ValidStringIds;
            IMobileServiceTable <ToDoWithStringId> table = GetClient().GetTable <ToDoWithStringId>();

            foreach (string testId in testIdData)
            {
                ToDoWithStringId item = new ToDoWithStringId()
                {
                    Id = testId, String = "Hey"
                };
                await table.InsertAsync(item);
            }

            string[] invalidIdData = IdTestData.EmptyStringIds.Concat(
                IdTestData.InvalidStringIds).Concat(
                new string[] { null }).ToArray();

            foreach (string invalidId in invalidIdData)
            {
                IEnumerable <ToDoWithStringId> results = await table.Where(p => p.Id == invalidId).ToEnumerableAsync();

                ToDoWithStringId[] items = results.ToArray();

                Assert.AreEqual(0, items.Count());
            }

            foreach (string testId in testIdData)
            {
                ToDoWithStringId item = new ToDoWithStringId()
                {
                    Id = testId
                };
                await table.DeleteAsync(item);
            }
        }
Beispiel #22
0
        public async void showWalletBalance()
        {
            //Check if wallet has enough balance
            IMobileServiceTable <Wallet> walletData = client.GetTable <Wallet>();

            //Getting the Wallet details from the Database
            List <Wallet> currentBalance = await walletData.Where
                                               (item => item.Email == client.CurrentUser.UserId).ToListAsync();


            var balanceTextView = FindViewById <TextView>(Resource.Id.balance);

            if (currentBalance.Count > 0)
            {
                wallet = currentBalance[0];
                balanceTextView.Append("Current Balance: RM " + wallet.Balance + ".00");
            }
            else
            {
                wallet.Balance = "0";
                balanceTextView.Append("Current Balance: RM " + wallet.Balance + ".00");
            }
        }
Beispiel #23
0
        private async Task GetUsuario()
        {
            vm.Running = true;
            var client = new MobileServiceClient("https://coepticket.azurewebsites.net");

            IMobileServiceTable <Usuarios> table = client.GetTable <Usuarios>();
            List <Usuarios> items = await table.Where(u => u.Email == Settings.UserName)
                                    .Take(1)
                                    .ToListAsync();

            item = new ObservableCollection <Usuarios>(items);

            vm.Correo       = item[0].Email;
            vm.Nombre       = item[0].Nombre;
            vm.Apellidos    = item[0].Apellido;
            vm.Profesion    = item[0].Profesion;
            vm.ImagenPerfil = item[0].Imagen; //Despues cambiar
            vm.CV           = item[0].CV;
            vm.ID           = item[0].Id;


            vm.Running = false;
        }
Beispiel #24
0
        public async Task GetdataAsync()
        {
            try
            {
                IMobileServiceTableQuery <UserReg> query = DataTable
                                                           .Where(ur => ur.Email == tempdata.Loginas);
                // .Select(todoItem => todoItem.InvoiceSubject);

                List <UserReg> items = await query.ToListAsync();



                name.Text         = string.Format("{0} {1}", items[0].FirstName, items[0].LastName);
                Email.Text        = items[0].Email;
                Address.Text      = items[0].Address;
                PhoneNumber.Text  = items[0].PhoneNumber;
                ServiceType1.Text = Convert.ToString(items[0].ServiceType);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Sync error: {0}", new[] { e.Message });
            }
        }
Beispiel #25
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.deleteWeighs);
            // Create your application here
            MobileServiceClient client = ToDoActivity.CurrentActivity.CurrentClient;

            try
            {
                weighTableRef = client.GetTable <weighTable>();
                DateTime today = DateTime.Now;
                //DateTime earliestDate = today.AddDays(-1);
                DateTime earliestDate = today.AddMinutes(-30);

                //get all the to be deleted weights -  the weights before the specified date
                var toBeDeleted = await weighTableRef.Where(item => (item.username == ourUserId) && (item.createdAt <= earliestDate)).ToListAsync();


                if (toBeDeleted.Count == 0)
                {
                    CreateAndShowDialog("No weights were found prior to the specified date", "Cannot Delete");
                }
                else
                {
                    foreach (weighTable weight in toBeDeleted)
                    {
                        await weighTableRef.DeleteAsync(weight);
                    }
                    //TODO:  go back to previous activity
                    CreateAndShowDialog("", "Deleted Successfully");
                }
            }
            catch (Exception e)
            {
                CreateAndShowDialog(e, "Error");
            }
        }
Beispiel #26
0
        public async void ObrisiProjekt(object parametar)
        {
            IMobileServiceTable <Projekti> usersTable = App.MobileService.GetTable <Projekti>();

            if (Pro == null)
            {
                return;
            }
            String idProjekta = Pro.ID1;

            for (int i = 0; i < BatNet.Projekti.Count; i++)
            {
                if (BatNet.Projekti.ElementAt(i) == Pro)
                {
                    BatNet.Projekti.RemoveAt(i);
                }
            }
            for (int i = 0; i < BatNet.Korisnici.Count; i++)
            {
                for (int j = 0; j < BatNet.Korisnici.ElementAt(i).Projekti.Count; j++)
                {
                    if (BatNet.Korisnici.ElementAt(i).Projekti.ElementAt(j).ID1.Equals(idProjekta))
                    {
                        BatNet.Korisnici.ElementAt(i).Projekti.RemoveAt(j);
                    }
                }
            }
            List <Projekti> projekat = await usersTable.Where(u => u.id == idProjekta).ToListAsync();

            if (projekat.Count > 1)
            {
                Debug.WriteLine("Big mistake! Stahp!");
                return;
            }
            projekat.ElementAt(0).obrisan = true;
            await usersTable.UpdateAsync(projekat.ElementAt(0));
        }
        private async void update(object sender, RoutedEventArgs e)
        {
            var pstudent = await todoTable
                           .Where(t => t.username == s).ToCollectionAsync();

            pstudent[0].attendance = int.Parse(textBox1.Text);
            String tt = comboBox.Items[comboBox.SelectedIndex].ToString();

            if (tt.Equals("English"))
            {
                pstudent[0].engp = int.Parse(textBox.Text);
            }
            else if (tt.Equals("Hindi"))
            {
                pstudent[0].hinp = int.Parse(textBox.Text);
            }
            else if (tt.Equals("Maths"))
            {
                pstudent[0].mathp = int.Parse(textBox.Text);
            }
            else if (tt.Equals("Science"))
            {
                pstudent[0].scip = int.Parse(textBox.Text);
            }
            else if (tt.Equals("Social Science"))
            {
                pstudent[0].ssp = int.Parse(textBox.Text);
            }
            else
            {
                pstudent[0].csp = int.Parse(textBox.Text);
            }

            await todoTable.UpdateAsync(pstudent[0]);

            this.Frame.Navigate(typeof(MainPage), null);
        }
Beispiel #28
0
        public async Task GetdataAsync()
        {
            try
            {
                IMobileServiceTableQuery <WorkOrder> query = DataTable
                                                             .Where(ur => ur.ServiceProviderID == tempdata.Loginas && ur.WorkOrderSubject == tempdata.selected_WorkOrderSubject);
                // .Select(todoItem => todoItem.InvoiceSubject);

                List <WorkOrder> items = await query.ToListAsync();

                // EmployeeView.ItemsSource = items2;

                // finalname.Text = string.Format("{0}-{1}", items2[0].FirstName, items2[0].LastName);

                lb1.Text = string.Format("{0} :- {1}", "Subject", items[0].WorkOrderSubject);
                lb2.Text = string.Format("{0} :- {1}", "DueDate", items[0].DueDate);
                lb3.Text = string.Format("{0} :- {1}", "Description", items[0].Description);
                lb4.Text = string.Format("{0} :- {1}", "Current Status", items[0].Status);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Sync error: {0}", new[] { e.Message });
            }
        }
        private async void Button_Click_1Async(object sender, RoutedEventArgs e)
        {
            MobileServiceInvalidOperationException exception = null;

            try
            {
                // This code refreshes the entries in the list view by querying the TodoItems table.
                // The query excludes completed TodoItems.
                items = await userTable
                        .Where(userTable => userTable.User_Email == Uemail.Text && userTable.Password == password.Password)
                        .Select(userTable => userTable.id).ToListAsync();

                //similar to select the ID from usertable where useremail is equal to email textbox text and password is equal to password text box
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
            }
            else
            {
                if (items.Count == 1)
                {
                    Frame.Navigate(typeof(BlankPage5), Uemail.Text);
                }
                else
                {
                    MessageDialog msgDialog = new MessageDialog("Email or password is incorrect !!");
                    await msgDialog.ShowAsync();
                }
            }
        }
Beispiel #30
0
        public async void GetContent()
        {
            try
            {
                Content = "正在获取小贴士\n\n将本应用Pin到主界面会有动态瓷贴提示哦!";
                todoTable = App.MobileService.GetTable<Tip>();

                Random r = new Random();
                int x = r.Next(LEASTTIPID, BIGGESTTIPID);

                items = await todoTable.Where(Tip => Tip.id == x).ToCollectionAsync();

                if (items.Count > 0)
                    this.Content = items[0].Content;
                else
                    this.Content = "获取小贴士失败……\n\n将本应用Pin到主界面会有动态瓷贴提示哦!";
            }
            catch (Exception)
            {
                this.Content = "获取小贴士失败……\n\n将本应用Pin到主界面会有动态瓷贴提示哦!";
            }

            //return "请连接网络以获取小贴士";
        }
Beispiel #31
0
        public async Task QueryAsync(string user, string pass)
        {
            List <Login> lista = new List <Login>();

            try
            {
                string password = Encrypt(pass);
                //In this part we do a linq query to get the correct information.
                lista = await userTableObject.Where(userTableObj => userTableObj.User == user && userTableObj.Password == password).ToListAsync();

                var obj = lista[0];
                LoginActivity.Obj = lista[0];
                System.Diagnostics.Debug.WriteLine("Welcome back " + obj.User + " Tu id es: " + obj.IdC, " Intelligent Identificator Security System");
                if (lista.Count == 1)
                {
                    LoginActivity.IdC      = Convert.ToInt32(obj.IdC);
                    LoginActivity.IsLogged = true;
                }
            }
            catch (Exception)
            {
                LoginActivity.IsLogged = false;
            }
        }
        public async Task FilterReadAsyncWithEmptyStringIdAgainstIntegerIdTable()
        {
            await EnsureEmptyTableAsync <ToDoWithIntId>();

            IMobileServiceTable <ToDoWithIntId> table = GetClient().GetTable <ToDoWithIntId>();
            List <ToDoWithIntId> integerIdItems       = new List <ToDoWithIntId>();

            for (var i = 0; i < 10; i++)
            {
                ToDoWithIntId item = new ToDoWithIntId()
                {
                    String = i.ToString()
                };
                await table.InsertAsync(item);

                integerIdItems.Add(item);
            }

            string[] testIdData = new string[] { "", " ", null };

            IMobileServiceTable <ToDoWithStringIdAgainstIntIdTable> stringIdTable = GetClient().GetTable <ToDoWithStringIdAgainstIntIdTable>();

            foreach (string testId in testIdData)
            {
                IEnumerable <ToDoWithStringIdAgainstIntIdTable> results = await stringIdTable.Where(p => p.Id == testId).ToEnumerableAsync();

                ToDoWithStringIdAgainstIntIdTable[] items = results.ToArray();

                Assert.AreEqual(0, items.Length);
            }

            foreach (ToDoWithIntId integerIdItem in integerIdItems)
            {
                await table.DeleteAsync(integerIdItem);
            }
        }
        // Function to buy item
        private async void BuyItem(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (online)
            {
                

                var itemId = ((Button)sender).Tag.ToString();

                string itemName = null;
                foreach (var objects in ((Grid)((Button)sender).Parent).Children)
                {
                    if (objects is TextBlock)
                    {
                        itemName = ((TextBlock)objects).Text;
                    }
                }


                // Remove item corresponding to itemId/itemName from database.
                XmlTaskService.DeleteTask(itemName, "tasks.xml");
                // Remove item corresponding to itemId/itemName from XML tables.

                itemTable = MobileService.GetTable<Items>();

                var parent = (ListBox)((Grid)((Button)sender).Parent).Parent;
                parent.Items.Remove(((Grid)((Button)sender).Parent));
                
                
                try
                {

                    var myList1 = await itemTable.Where(itemabc => itemabc.Id.ToString() == itemId).ToListAsync();

                    await itemTable.DeleteAsync(myList1[0]);
                    var uid = myList1[0].User_Id;
                    var todoItem = new Notify
                    {
                        Message = user_name + " has bought " + itemName + " for you",
                        Type = "",
                        User_Id = uid
                    };
                    var notifyTable = MobileService.GetTable<Notify>();
                    await notifyTable.InsertAsync(todoItem);
               
               
                }
                catch
                {
                    return;
                }

               

            }
        }
Beispiel #34
0
        private async void LoadProfile()
        {
           
                LiveConnectClient client = new LiveConnectClient(Connection.Session);

                LiveOperationResult liveOpResult = await client.GetAsync("me");

                //IDictionary<string, object> myResult = liveOpResult.Result;
                //for (int i = 0; i < myResult.Count; i++)
                //{
                //    Debug.WriteLine(myResult.ElementAt(i).Key + " " + myResult.ElementAt(i).Value);
                //}
                dynamic dynResult = liveOpResult.Result;

                // logIn.Text = Connection.UserName;
                string id = Connection.MobileService.CurrentUser.UserId;
                string LiveSDKId = dynResult.id;
                string first_name = dynResult.first_name;
                string last_name = dynResult.last_name;
                string link = dynResult.link;
                string gender = dynResult.gender;
                string email = dynResult.emails.preferred;

                liveOpResult = await client.GetAsync("me/picture");
                dynamic dynResult2 = liveOpResult.Result;
                var image = dynResult2.location;// to get the profile photo

                List<User> usersList = new List<User>();
                User = Connection.MobileService.GetTable<User>();


                try
                {
                    usersList = await User.Where(p => p.UserId == id).ToListAsync();
                }
                catch (MobileServiceInvalidOperationException ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                if (usersList.Count == 0)
                {
                    try
                    {
                        await User.InsertAsync(new User
                        {
                            isAdmin  = false,
                            UserId = id,
                            LiveSDKID = LiveSDKId,
                            //UserId = App.MobileService.CurrentUser.UserId,
                            CreatedDate = DateTime.Now,
                            ImageUri = dynResult2.location,
                            FName = first_name,
                            LName = last_name,
                            Email = email,
                            Type = String.Empty
                        });

                        usersList = await User.Where(p => p.UserId == id).ToListAsync();
                        Connection.User = usersList.First();
                    }
                    catch (MobileServiceInvalidOperationException e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                }
                else
                {
                    Connection.User = usersList.First();
                }

                Connection.UserName = dynResult.name;
                Connection.ImageUri = dynResult2.location;



               //await  Windows.UI.Xaml.DependencyObject.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
               // {
                    RegisterDeviceAsync();

                    AddContacts();
               // });

                   
                
               
                

        }
Beispiel #35
0
        public async  void AddContacts()
        {
            //create new LiveSDK contact

            LiveConnectClient client = new LiveConnectClient(Connection.Session);

            LiveOperationResult liveOpResult = await client.GetAsync("me/contacts");

            IDictionary<string, object> myResult = liveOpResult.Result;
            List<object> data = null;
            IDictionary<string, object> contact;
            string contact_fname = String.Empty;
            string contact_lname = String.Empty;
            Dictionary<string, string> contactList = new Dictionary<string, string>();

            if (myResult.ContainsKey("data"))
            {
                 data = (List<object>)myResult["data"];
                 for (int i = 0; i < data.Count; i++)
                 {
                     contact = (IDictionary<string, object>)data[i];
                     if (contact.ContainsKey("first_name"))
                     {
                         //contactList.ElementAt(i).Key =
                        
                         contact_fname = (string) contact["first_name"];
                     }
                     if(contact.ContainsKey("last_name"))
                     {
                         contact_lname = (string)contact["last_name"];
                     }

                     if(contact_fname!=String.Empty && contact_lname!=String.Empty)
                     {
                         contactList.Add(contact_fname, contact_lname);

                         contact_fname = String.Empty;
                         contact_lname = String.Empty;
                     }

                 }
            }

            List<User> usersList = new List<User>();
            User = Connection.MobileService.GetTable<User>();

            usersList = await User.Where(p => p.UserId != Connection.MobileService.CurrentUser.UserId ).ToListAsync();
            for (int i = 0; i < usersList.Count; i++)
            {
                if (!(contactList.ContainsKey(usersList.ElementAt(i).FName) && contactList.ContainsValue(usersList.ElementAt(i).LName)))
                {
                    contact = new Dictionary<string, object>();
                    contact.Add("first_name", usersList.ElementAt(i).FName);
                    contact.Add("last_name", usersList.ElementAt(i).LName);
                    // contact.Add("emails.preferred", usersList.ElementAt(i).Email);
                    contact.Add("emails", new Dictionary<string, object> {
                {"account",usersList.ElementAt(i).Email },
                {"preferred",usersList.ElementAt(i).Email },
                { "personal", usersList.ElementAt(i).Email},
                {"business", usersList.ElementAt(i).Email},
                {"other", usersList.ElementAt(i).Email} 
                });

                    await client.PostAsync("me/contacts", contact);

                }
            }
            // get List of users loop
            //  var contact = new Dictionary<string, object>();
            // contact.Add("first_name", "Michael");
            // contact.Add("last_name", "Crump");
            //contact.Add( "emails.preferred", "*****@*****.**");
            //client.PostAsync("me/contacts", contact);
            MainPage.Success2 = true;

        }
        private async void FillFriendsInformation(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (((Pivot)sender).SelectedIndex == 0)
            {
                RefreshTodoItems();
            } else  if (((Pivot)sender).SelectedIndex == 1)
            {
                FriendsListPanel.Children.Clear();

                if (online)
                {
                    relationsTable = MobileService.GetTable<Relations>();
                    var myList1 = await relationsTable.Where(itemabc => itemabc.Sender_Id == user_id).ToListAsync();
                    var myList2 = await relationsTable.Where(item2 => item2.Receiver_Id == user_id).ToListAsync();

                    List<int> userList = new List<int>();
                    foreach (var val in myList1)
                    {
                        if (val.Receiver_Id != user_id) userList.Add(val.Receiver_Id);
                    }

                    foreach (var val in myList2)
                    {
                        if (val.Sender_Id != user_id) userList.Add(val.Sender_Id);
                    }

                    itemTable = MobileService.GetTable<Items>();
                    foreach (var user in userList)
                    {
                        var items = await itemTable.Where(user2 => ((user2.User_Id == user) && (user2.shared == true))).ToListAsync();
                        var itemList = new Dictionary<int, String>();
                        foreach (var item in items)
                        {
                            itemList.Add(item.Id, item.Text);
                        }
                        userTable = MobileService.GetTable<Users>();
                        var list = await userTable.Where(user3 => (user3.Id == user)).ToListAsync();

                        AddFriendInformation(list[0].Name, user, itemList);
                    }
                }
                else
                {
                    AddFriendInformation("Unavailable, check connectivity", 0, null);
                }
            }
            else if (((Pivot)sender).SelectedIndex == 2)
            {
                RefreshMyCart();
    			RefreshTheirCart();
            }
        }
		private async void RefreshTheirCart()
		{
            if(online)
            {

                relationsTable = MobileService.GetTable<Relations>();

                var myList1 = await relationsTable.Where(itemabc => itemabc.Sender_Id == user_id).ToListAsync();

                var myList2 = await relationsTable.Where(item2 => item2.Receiver_Id == user_id).ToListAsync();

                
                List<int> userList= new List<int>();
                foreach (var val in myList1)
                {
                    userList.Add(val.Receiver_Id);
                }
                foreach (var val in myList2)
                {
                    userList.Add(val.Sender_Id);
                }

                itemTable = MobileService.GetTable<Items>();

                List<Items> final = new List<Items>();
                var tempList= new List<Items>();
                foreach(var val in userList)
                {
                    Debug.WriteLine("Refresh their3");
                    tempList = await itemTable.Where(item2 => item2.User_Id == val).ToListAsync();
                    foreach(var val2 in tempList)
                    {
                        if(val2.shared == true)final.Add(val2);
                    }
                }
                foreach (Items buffitem in final)
                {
                    AddNewItemToBuyGrid(buffitem.Text, buffitem.Id);
                }
			
             }

		}