Exemplo n.º 1
0
        private async void LoadTraps()
        {
            try
            {
                var response = await PurchaseApiService.ListAvailableTraps();

                if (response != null)
                {
                    availableTraps = response;

                    LoadGooglePrices();
                }
                else
                {
                    progressDialog.Cancel();

                    HomeActivity homeActivity = (HomeActivity)Activity;
                    homeActivity.OnSectionAttached(HomeActivity.HOME_MENU_INDEX, true);
                }

                if (!AppStatus.UserLogged.ContainsTraps())
                {
                    lbl_title_my_traps.Visibility = ViewStates.Gone;
                }
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }
        }
Exemplo n.º 2
0
        //TO DO move as much as possible below here to a viewmodel so that it can be unit tested
        private async void RefreshBtn_Click(object sender, EventArgs e)
        {
            if (!locationManager.HasPermissions(this))
            {
                Toast.MakeText(this, "The app needs permissions to location services.", ToastLength.Long).Show();
                return;
            }

            if (!locationManager.HasGooglePlayServicesInstalled(this))
            {
                Toast.MakeText(this, "The phone does not have google play services installed.", ToastLength.Long).Show();
                return;
            }

            progressDialog.Show();

            var userlocation = await locationManager.GetLastLocationFromDevice();

            if (userlocation == null)
            {
                progressDialog.Cancel();
                Toast.MakeText(this, "Error retrieving your location, make sure location is set in your settings", ToastLength.Long).Show();
                return;
            }

            await GetAndPopulateLocations(userlocation);
        }
Exemplo n.º 3
0
 public void OnFailure(Request request, IOException iOException)
 {
     dialog.Cancel();
     RunOnUiThread(() => btTryAgain.Visibility = Android.Views.ViewStates.Visible);
     handler.Post(() =>
     {
         Toast.MakeText(this, "Fail Internet Connection", ToastLength.Short).Show();
     });
 }
Exemplo n.º 4
0
 protected override void OnSaveInstanceState(Bundle outState)
 {
     if (verificandoLogin)
     {
         outState.PutBoolean("verificandoLogin", verificandoLogin);
         progress.Cancel();
     }
     base.OnSaveInstanceState(outState);
 }
Exemplo n.º 5
0
        private async void SendArmedTrap()
        {
            try
            {
                progressDialog = ProgressDialog.Show(Activity, Resources.GetString(MyTrap.Droid.Resource.String.loading), Resources.GetString(MyTrap.Droid.Resource.String.arming_trap));

                ArmedTrapApiRequest armedTrap = new ArmedTrapApiRequest();

                armedTrap.NameKey   = selectedTrap.NameKey;
                armedTrap.Latitude  = (float)lastLocation.Latitude;
                armedTrap.Longitude = (float)lastLocation.Longitude;

                var response = await TrapApiService.Arm(armedTrap);

                if (ResponseValidator.Validate(response, Activity))
                {
                    ShowAlertArmedTrapSuccessfuly();
                }

                progressDialog.Cancel();
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }
        }
Exemplo n.º 6
0
        private async void ShowRouteToPlace(Place place)
        {
            ProgressDialog pleaseWaitDialog = new ProgressDialog(this);

            pleaseWaitDialog.SetMessage(GetString(Resource.String.please_wait));
            pleaseWaitDialog.SetCancelable(false);
            pleaseWaitDialog.Show();

            try
            {
                MapFragment mapFragment = FragmentManager.FindFragmentByTag <MapFragment>("MAP_FRAGMENT");

                nearestPlace = place;
                Route route = await DirectionsService.GetShortestRoute(
                    mapFragment.MyLocation, place.geometry.location);

                mapFragment.DrawRouteToPlace(route, nearestPlace);
            }
            catch (ApiCallException)
            {
            }
            catch (DirectionsException)
            {
            }
            finally
            {
                pleaseWaitDialog.Cancel();
            }
        }
Exemplo n.º 7
0
 public static void HideInputDialog()
 {
     if (dialog != null)
     {
         dialog.Cancel();
     }
 }
Exemplo n.º 8
0
 protected override void OnPostExecute(Java.Lang.Object result)
 {
     proDialg.Cancel();
     if (result.ToString() != "OK")
     {
         Toast.MakeText(mainActivity, "Init failure!", ToastLength.Short);
     }
 }
Exemplo n.º 9
0
        private async void Login()
        {
            if (!Validate())
            {
                OnLoginFailed();
                return;
            }

            _loginButton.Enabled = false;

            var progressDialog = new ProgressDialog(this, Resource.Style.AppTheme_Dark_Dialog);

            progressDialog.Indeterminate = true;
            progressDialog.SetMessage(GetString(Resource.String.SigningIn));
            progressDialog.Show();

            var email    = _emailText.Text;
            var password = _passwordText.Text;


            try
            {
                var apiKey = GetString(Resource.String.ApiKey); // Он реально меняется
                using (var authProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey)))
                {
                    var auth = await authProvider.SignInWithEmailAndPasswordAsync(email, password);

                    SaveUserId(auth.FirebaseToken);
                    OnLoginSuccess();
                }
            }
            catch (HttpRequestException)
            {
                progressDialog.Cancel();
                OnLoginFailed(GetString(Resource.String.SignInError));
            }
            catch (Exception)
            {
                progressDialog.Cancel();
                OnLoginFailed(GetString(Resource.String.Error));
            }
        }
Exemplo n.º 10
0
 private void Initialize()
 {
     mDialog = new ProgressDialog(_context);
     mDialog.SetMessage(_message);
     mDialog.Indeterminate = true;
     mDialog.SetCancelable(_cancelable);
     if (_cancelable)
     {
         mDialog.SetCanceledOnTouchOutside(true);
         mDialog.CancelEvent += (sender, args) => mDialog.Cancel();
     }
 }
Exemplo n.º 11
0
 protected override void OnPostExecute(Java.Lang.Object obj)
 {
     if (obj.ToString() != "OK")
     {
         Toast.MakeText(mContext, "init failuer", ToastLength.Short).Show();
     }
     else
     {
         Toast.MakeText(mContext, "init OK", ToastLength.Short).Show();
     }
     pro.Cancel();
 }
Exemplo n.º 12
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Datos);

            if (Intent != null)
            {
                Email = Intent.GetStringExtra("email");
                Pass  = Intent.GetStringExtra("pass");
            }

            lvEvidencia = FindViewById <ListView>(Resource.Id.lvEvidencia);
            var txName = FindViewById <TextView>(Resource.Id.txName);

            txName.Text = Pass;

            lvEvidencia.ItemClick += (sender, e) =>
            {
                var ActivityIntent =
                    new Intent(this, typeof(EvidencesDetail));
                ActivityIntent.PutExtra("Email", Email);
                ActivityIntent.PutExtra("Pass", Pass);
                ActivityIntent.PutExtra("EvidenceID", evidencias.Evidences[e.Position].EvidenceID);
                ActivityIntent.PutExtra("Title", evidencias.Evidences[e.Position].Title);
                ActivityIntent.PutExtra("Status", evidencias.Evidences[e.Position].Status);
                StartActivity(ActivityIntent);
            };

            evidencias = new EvidencesFragment();
            if (evidencias.Evidences == null)
            {
                progress = new Android.App.ProgressDialog(this);
                progress.Indeterminate = true;
                progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner);
                progress.SetMessage("Please...");
                progress.SetCancelable(false);
                progress.Show();

                var fragmentTransaction = this.FragmentManager.BeginTransaction();
                fragmentTransaction.Add(evidencias, "Evidences");
                fragmentTransaction.Commit();

                GetEvidences();
                progress.Cancel();
            }
            else
            {
                lvEvidencia.Adapter = evidencias.EvidencesAdapter;
            }
        }
Exemplo n.º 13
0
        public void OnLocationChanged(Location location)
        {
            _latEditText.Text  = location.Latitude.ToString();
            _longEditText.Text = location.Longitude.ToString();

            var geocdr    = new Geocoder(this);
            var addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

            if (addresses.Any())
            {
                UpdateAddressFields(addresses.First());
            }

            _progressDialog.Cancel();
        }
Exemplo n.º 14
0
        public void OnLocationChanged(Location location)
        {
            _latEditText.Text  = location.Latitude.ToString();
            _longEditText.Text = location.Longitude.ToString();

            Console.WriteLine("location changed {0} {1} ", location.Latitude.ToString(), location.Longitude.ToString());

            Geocoder        geocdr    = new Geocoder(this);
            IList <Address> addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

            if (addresses.Any())
            {
                UpdateAddressFields(addresses.First());
            }

            _progressDialog.Cancel();
        }
Exemplo n.º 15
0
        public async void TryBuy(AvailableTrapApiResult availableTrap)
        {
            progressDialog = ProgressDialog.Show(Activity, Resources.GetString(MyTrap.Droid.Resource.String.loading), Resources.GetString(MyTrap.Droid.Resource.String.registering_purchase));

            try
            {
                BuyIntentApiRequest intent = new BuyIntentApiRequest()
                {
                    AvailableTrapId = availableTrap.Id, StoreKey = availableTrap.KeyGoogle
                };

                await PurchaseApiService.InsertBuyIntent(intent);

                pendingBuyIntent = intent;

                Product product = null;

                foreach (var itemGoogle in products)
                {
                    if (itemGoogle.ProductId == availableTrap.KeyGoogle)
                    {
                        product = itemGoogle;
                        break;
                    }
                }

                if (product != null)
                {
                    //product.ProductId = "android.test.purchased";
                    //product.ProductId = "android.test.canceled";
                    //product.ProductId = "android.test.refunded";

                    //await RegisterPurchase(intent);

                    _serviceConnection.BillingHandler.BuyProduct(product);
                }
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }

            progressDialog.Cancel();
        }
Exemplo n.º 16
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            //这个效果就是登陆或者其他的加载提示框,如果这里用 ProgressDialog.Builder 也是可以,但是要自定义显示信息,包括图片信息等等。
            ProgressDialog p_dialog = new ProgressDialog(this);

            p_dialog.SetMessage("正在加载……");
            p_dialog.Show();

            //等加载完成后再让其消失
            Thread newThread = new Thread(() =>
            {
                Thread.Sleep(2000);  //模拟加载数据,当前进程延迟2秒

                Button btn = FindViewById <Button>(Resource.Id.button1);
                btn.Click += Btn_Click;

                Button btn2 = FindViewById <Button>(Resource.Id.button2);
                btn2.Click += Btn2_Click;

                Button btn3 = FindViewById <Button>(Resource.Id.button3);
                btn3.Click += Btn3_Click;

                Button btn4 = FindViewById <Button>(Resource.Id.button4);
                btn4.Click += Btn4_Click;

                Button btn5 = FindViewById <Button>(Resource.Id.button5);
                btn5.Click += Btn5_Click;

                Button btn6 = FindViewById <Button>(Resource.Id.button6);
                btn6.Click += Btn6_Click;

                Button btn7 = FindViewById <Button>(Resource.Id.button7);
                btn7.Click += Btn7_Click;

                // cancel和dismiss方法本质都是一样的,都是从屏幕中删除Dialog,唯一的区别是
                // 调用cancel方法会回调DialogInterface.OnCancelListener如果注册的话,dismiss方法不会回掉
                p_dialog.Cancel();
            });

            newThread.Start();
        }
 // 模拟长时间执行的任务
 private void RunTask(bool showProgress)
 {
     System.Threading.Tasks.Task.Run(() =>
     {
         while (progress < 100)
         {
             dialog.Progress = progress++;
             if (showProgress)
             {
                 RunOnUiThread(() =>
                 {
                     dialog.SetMessage("正在下载……" + progress + "%");
                 });
             }
             System.Threading.Thread.Sleep(100);
         }
         dialog.Cancel();
     });
 }
Exemplo n.º 18
0
        public void OnLocationChanged(Location location)
        {
            _latEditText.Text  = location.Latitude.ToString();
            _longEditText.Text = location.Longitude.ToString();
            //Console.WriteLine ("In OnLocationChanged...");
            Geocoder        geocdr    = new Geocoder(this);
            IList <Address> addresses = geocdr.GetFromLocation(location.Latitude, location.Longitude, 5);

            if (addresses.Any())
            {
                UpdateAddressFields(addresses.First());
            }

            _progressDialog.Cancel();
            _obtainingLocation = false;

            //Tom: 加入訊息 20141031
            Toast toast = Toast.MakeText(this, "定位完成。若地址不完全正確,請再手動修正。", ToastLength.Short);

            toast.Show();
            _addrEditText.RequestFocus();
        }
Exemplo n.º 19
0
 public void HideLoading()
 {
     progress.Cancel();
 }
Exemplo n.º 20
0
 protected override void Complete(bool result)
 {
     _ProgressDialog.Cancel();
 }
Exemplo n.º 21
0
        private async void clickBtnLogIn(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(username.Text) || string.IsNullOrEmpty(username.Text))
            {
                Snackbar bar = Snackbar.Make(parentLayout, "Fill username", Snackbar.LengthLong);
                bar.SetText(Html.FromHtml("<font color=\"#000000\">Fill username</font>"));
                Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                layout.SetMinimumHeight(100);
                layout.SetBackgroundColor(Android.Graphics.Color.White);
                layout.TextAlignment = TextAlignment.Center;
                layout.ScrollBarSize = 16;
                bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                bar.SetDuration(Snackbar.LengthLong);
                bar.SetAction("Ok", (v) => { });
                bar.Show();
            }
            else if (string.IsNullOrWhiteSpace(password.Text) || string.IsNullOrEmpty(password.Text))
            {
                Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Fill password</font>"), Snackbar.LengthLong);
                Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                layout.SetMinimumHeight(100);
                layout.SetBackgroundColor(Android.Graphics.Color.White);
                layout.TextAlignment = TextAlignment.Center;
                layout.ScrollBarSize = 16;
                bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                bar.SetDuration(Snackbar.LengthLong);
                bar.SetAction("Ok", (v) => { });
                bar.Show();
            }
            else
            {
                var progressDialog = new ProgressDialog(this);
                try
                {
                    progressDialog.SetIcon(2130968582);
                    progressDialog.SetCancelable(true);
                    progressDialog.SetMessage("Please wait!");
                    progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
                    progressDialog.Show();

                    var client        = new HttpClient();
                    var keyValueLogIn = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("username", username.Text),
                        new KeyValuePair <string, string>("password", password.Text),
                        new KeyValuePair <string, string>("grant_type", "password")
                    };
                    var request = new HttpRequestMessage(HttpMethod.Post, "UrlApiToken");
                    request.Content = new FormUrlEncodedContent(keyValueLogIn);
                    var response = await client.SendAsync(request);

                    var content = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        TokenModel tokenFromServer = JsonConvert.DeserializeObject <TokenModel>(content);
                        var        jsonContent     = JsonConvert.SerializeObject(username.Text);
                        var        LogIncontent    = new StringContent(jsonContent, Encoding.ASCII, "application/json");

                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenFromServer.access_token);

                        response = await client.PostAsync("UrlApi" + "api/Account/userdata", LogIncontent);

                        var userData = await response.Content.ReadAsStringAsync();

                        User user = JsonConvert.DeserializeObject <User>(userData);

                        var userSession = new UserSession
                        {
                            FirstName  = user.FirstName,
                            LastName   = user.LastName,
                            userId     = user.userId,
                            Token      = tokenFromServer.access_token,
                            user_image = user.user_image
                        };
                        con.Insert(userSession);
                        progressDialog.Cancel();
                        StartActivity(typeof(MainActivity));
                    }
                    else
                    {
                        LogInError logInError      = JsonConvert.DeserializeObject <LogInError>(content);
                        var        alertLogInError = new Android.App.AlertDialog.Builder(this);
                        alertLogInError.SetTitle(logInError.error);
                        alertLogInError.SetMessage(logInError.error_description);
                        username.Text = "";
                        password.Text = "";

                        Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">" + logInError.error + " - " + logInError.error_description + "</font>"), Snackbar.LengthLong);
                        Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                        layout.SetMinimumHeight(100);
                        layout.SetBackgroundColor(Android.Graphics.Color.White);
                        layout.TextAlignment = TextAlignment.Center;
                        layout.ScrollBarSize = 16;
                        bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                        bar.SetDuration(Snackbar.LengthLong);
                        bar.SetAction("Ok", (v) => { });
                        bar.Show();

                        progressDialog.Cancel();
                    }
                }
                catch (HttpRequestException httpEx)
                {
                    Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Please check your internet connection!</font>"), Snackbar.LengthLong);
                    Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                    layout.SetMinimumHeight(100);
                    layout.SetBackgroundColor(Android.Graphics.Color.White);
                    layout.TextAlignment = TextAlignment.Center;
                    layout.ScrollBarSize = 16;
                    bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                    bar.SetDuration(Snackbar.LengthIndefinite);
                    bar.SetAction("Ok", (v) => { });
                    bar.Show();
                    progressDialog.Cancel();
                }
                catch (Exception ex)
                {
                    Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Error: " + ex + "</font>"), Snackbar.LengthLong);
                    Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                    layout.SetMinimumHeight(100);
                    layout.SetBackgroundColor(Android.Graphics.Color.White);
                    layout.TextAlignment = TextAlignment.Center;
                    layout.ScrollBarSize = 16;
                    bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                    bar.SetDuration(Snackbar.LengthIndefinite);
                    bar.SetAction("Ok", (v) => { });
                    bar.Show();
                    progressDialog.Cancel();
                }
            }
        }
Exemplo n.º 22
0
        public void DoLogin()
        {
            progressDialog = ProgressDialog.Show(this, "Please wait...", "Checking For Updates...", true);
            new Thread(new ThreadStart(delegate
            {
                //NotificationSystem.ShowNotification(this);


                string IpAdress       = GetIp();
                IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
                string ipAddress      = string.Empty;
                if (addresses != null && addresses[0] != null)
                {
                    ipAddress = addresses[0].ToString();
                }
                else
                {
                    ipAddress = null;
                }

                var android_id = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId);
                try
                {
                    WMSScanner.LoginResult lr = Constants._service.Login_Login(Operator, OperatorPass, Company, CompanyPass, "D", ipAddress, android_id, "Android Scanner", "");
                    if (lr.LoggedInCorrectly == true)
                    {
                        try
                        {
                            WMSScanner.DataTableResult dtr = Constants._service.CachScannerVariables(lr.WMSGuid);
                            if (dtr.Successful == true)
                            {
                                Update_Variables.NotFoundCode     = dtr.ResultDT.Rows[0]["SettingValue"].ToString().Trim();
                                Update_Variables.Trolly           = dtr.ResultDT.Rows[0]["Trolley"].ToString().Trim();
                                Update_Variables.MustScanPassword = dtr.ResultDT.Rows[0]["MustScanPass"].ToString().Trim();
                                Update_Variables.WMSWarehouse     = dtr.ResultDT.Rows[0]["WMSWarehouse"].ToString().Trim();
                                Update_Variables.AutoReplace      = dtr.ResultDT.Rows[0]["AutoReplace"].ToString().Trim();
                                Update_Variables.Company          = Company;
                                Update_Variables.MustCheckoutInsertPalletNumbering = dtr.ResultDT.Rows[0]["UsePalletNumberingOnCheckout"].ToString().Trim();


                                Update_Variables.MustFillLeadingZerosSalesOrder = bool.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosSalesOrder"].ToString().Trim());
                                Update_Variables.MustFillLeadingZerosInvoice    = bool.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosInvoice"].ToString().Trim());
                                Update_Variables.MustFillLeadingZerosPO         = bool.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosPO"].ToString().Trim());

                                Update_Variables.MustFillLeadingZerosSalesOrderAmount = int.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosSalesOrderAmount"].ToString());
                                Update_Variables.MustFillLeadingZerosInvoiceAmount    = int.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosInvoiceAmount"].ToString());
                                Update_Variables.MustFillLeadingZerosPOAmount         = int.Parse(dtr.ResultDT.Rows[0]["MustFillLeadingZerosPOAmount"].ToString());
                            }

                            WMSScanner.DataTableResult mustScanResult = Constants._service.CachScannerMustScan(lr.WMSGuid);
                            if (mustScanResult.Successful == true)
                            {
                                Update_Variables.MustScanItems = mustScanResult.ResultDT;
                            }

                            /*Will Exclude this for now testing still needs to be done*/
                            //WriteFiles(username, "", "");

                            Constants.CompanyPassword   = "";
                            Constants.Password          = "";
                            Constants.Operator          = Operator.Trim();
                            Update_Variables.WMSGuid    = new Guid(lr.WMSGuid);
                            Update_Variables.SysproGuid = lr.SysproGuid;

                            RunOnUiThread(() => Toast.MakeText(this, "Logged in to WMS Mobile Scanner.", ToastLength.Long).Show());

                            //we need to set the operator as active for today
                            WMSScanner.BoolResult activeflaged = Constants._service.Android_Update_Operator_Active_Flag(Update_Variables.WMSGuid.ToString());
                            if (activeflaged.Successful == false)
                            {
                                RunOnUiThread(() => progressDialog.Cancel());
                                ViewDialog alert = new ViewDialog();


                                RunOnUiThread(() => alert.showDialog(this, activeflaged.Message));
                                return;
                            }

                            //StartService(new Intent(this, typeof(CheckPickActivity)));
                            /*Start the WMS Check For New Assignment Notification*/
                            RunOnUiThread(() => progressDialog.Cancel());
                            var ScannerMenu = new Intent(this, typeof(MainActivity));/*New Main Activity*/
                            StartActivity(ScannerMenu);
                        }
                        catch (Exception ex)
                        {
                            RunOnUiThread(() => progressDialog.Cancel());
                            RunOnUiThread(() => Toast.MakeText(this, ex.Message.ToString(), ToastLength.Long));
                        }
                    }
                    else
                    {
                        RunOnUiThread(() => progressDialog.Hide());
                        ViewDialog alert = new ViewDialog();


                        RunOnUiThread(() => alert.showDialog(this, lr.Message + "Could not log in"));
                    }
                }
                catch (Exception ex)
                {
                    RunOnUiThread(() => progressDialog.Hide());
                    ViewDialog alert = new ViewDialog();


                    RunOnUiThread(() => alert.showDialog(this, ex.Message));
                }
            })).Start();
        }
Exemplo n.º 23
0
        private async Task RequestPokemons(string byUrl = "")
        {
            //await Task.Delay(5000);

            ProgressDialog pbar = new ProgressDialog(this);

            pbar.SetCancelable(false);
            pbar.SetMessage("Buscando Informações...");
            pbar.SetProgressStyle(ProgressDialogStyle.Horizontal);
            pbar.Indeterminate = true;
            pbar.SetProgressStyle(ProgressDialogStyle.Spinner);
            pbar.Show();

            //new Thread(new ThreadStart(async delegate
            //{

            try
            {
                fLista.Clear();
                Filtrar();

                await Task.Delay(3000);

                using (var client = new HttpClient())
                {
                    // envia a requisição GET
                    //var response = await client.GetStringAsync("https://pokeapi.co/api/v2/pokemon/").ConfigureAwait(true);
                    string response;

                    if (byUrl == "")
                    {
                        response = await client.GetStringAsync("https://pokeapi.co/api/v2/pokemon/?limit=25").ConfigureAwait(true);
                    }
                    else
                    {
                        response = await client.GetStringAsync(byUrl).ConfigureAwait(true);
                    }

                    // processa a resposta
                    GetPokemon getPokemon = JsonConvert.DeserializeObject <GetPokemon>(response);

                    fAnt  = "";
                    fNext = "";

                    if (!string.IsNullOrEmpty(getPokemon.Previous))
                    {
                        fAnt = getPokemon.Previous;
                    }

                    if (!string.IsNullOrEmpty(getPokemon.Next))
                    {
                        fNext = getPokemon.Next;
                    }


                    fLista = new List <ListaLocal>();
                    foreach (var result in getPokemon.Results)
                    {
                        ListaLocal lista = new ListaLocal();

                        lista.Name = result.name;

                        response = await client.GetStringAsync("http://pokeapi.co/api/v1/pokemon/" + result.name + "/").ConfigureAwait(true);

                        GetPokemonItem getPokemonItem = JsonConvert.DeserializeObject <GetPokemonItem>(response);
                        if (getPokemonItem != null)
                        {
                            lista.Image  = getPokemonItem.Sprites.front_default;
                            lista.Id     = getPokemonItem.Id;
                            lista.Height = getPokemonItem.Height;
                            lista.Weight = getPokemonItem.Weight;

                            foreach (var tipo in getPokemonItem.Types)
                            {
                                List <PokemonType> pokemonTypes = new List <PokemonType>();

                                pokemonTypes.Add(new PokemonType
                                {
                                    slot = tipo.slot,
                                    type = new NameAPIResource {
                                        name = tipo.type.name, url = tipo.type.url
                                    }
                                });

                                lista.Types = pokemonTypes;
                            }
                        }


                        fLista.Add(lista);
                    }
                }
            }
            catch (Exception ex)
            {
                Thread.Sleep(1000);
                this.RunOnUiThread(() =>
                {
                    this.Window.AddFlags(WindowManagerFlags.NotTouchable | WindowManagerFlags.NotTouchable);
                });
            }

            RunOnUiThread(() =>
            {
                Filtrar();
                pbar.Cancel();
                return;
            });

            //})).Start();
        }
Exemplo n.º 24
0
        protected override void OnPostExecute(Java.Lang.Object obj)
        {
            base.OnPostExecute(obj.ToString());

            pro.Cancel();
        }
Exemplo n.º 25
0
        private async void ShowRouteToNearestAddress(string query)
        {
            CheckInternetConnection();

            if (!string.IsNullOrWhiteSpace(query))
            {
                ProgressDialog pleaseWaitDialog = new ProgressDialog(this);
                pleaseWaitDialog.SetMessage(GetString(Resource.String.please_wait));
                pleaseWaitDialog.SetCancelable(false);
                pleaseWaitDialog.Show();

                try
                {
                    MapFragment mapFragment = FragmentManager.FindFragmentByTag <MapFragment>("MAP_FRAGMENT");

                    if (mapFragment.MyLocation == null)
                    {
                        AWidget.Toast.MakeText(this, GetString(Resource.String.my_location_unavaliable),
                                               AWidget.ToastLength.Short).Show();
                        return;
                    }

                    List <Place> places = await PlacesService.GetPlacesByQuery(query, mapFragment.MyLocation);

                    if (places.Count == 0)
                    {
                        AWidget.Toast.MakeText(this, GetString(Resource.String.no_places_found),
                                               AWidget.ToastLength.Short).Show();
                        return;
                    }

                    nearestPlace = null;
                    Route shortestRoute = null;
                    foreach (var place in places)
                    {
                        var route = await DirectionsService.GetShortestRoute(
                            mapFragment.MyLocation, place.geometry.location);

                        if (shortestRoute == null)
                        {
                            nearestPlace  = place;
                            shortestRoute = route;
                        }
                        else if (route.legs[0].distance.value < shortestRoute.legs[0].distance.value)
                        {
                            nearestPlace  = place;
                            shortestRoute = route;
                        }
                    }

                    mapFragment.DrawRouteToPlace(shortestRoute, nearestPlace);
                    OnPrepareOptionsMenu(actionBarMenu);
                    actionBarMenu.FindItem(Resource.Id.action_add_to_fav).SetVisible(true);
                }
                catch (ApiCallException)
                {
                }
                catch (NearbyPlacesSearchException)
                {
                }
                catch (DirectionsException)
                {
                }
                finally
                {
                    pleaseWaitDialog.Cancel();
                }
            }
        }
Exemplo n.º 26
0
 public void IErrorBook(string error)
 {
     Toast.MakeText(this, error, ToastLength.Long).Show();
     progress.Cancel();
 }
Exemplo n.º 27
0
        private void bLoad_Click(object sender, EventArgs e)
        {
            // Load URL contents and show a wait cursor in the meantime
            Cursor = Cursors.WaitCursor;

            try
            {
                using (WebClient client = new WebClient(this.UserAgent))
                {
                    string expandedUrl = null;
                    string postData    = null;

                    // Note: The Text property might modify the text value
                    using (ProgressDialog dialog = new ProgressDialog("Loading URL", "Please wait while the content is being downloaded..."))
                    {
                        dialog.OnDoWork = delegate
                        {
                            expandedUrl = CurrentVariable.ExpandedUrl;
                            if (dialog.Cancelled)
                            {
                                return(false);
                            }
                            client.SetPostData(CurrentVariable);
                            postData = client.PostData;
                            CurrentVariable.TempContent = client.DownloadString(new Uri(expandedUrl));
                            return(true);
                        };
                        dialog.OnCancel = delegate {
                            dialog.Cancel();
                        };
                        dialog.ShowDialog(this);

                        // Did an error occur?
                        if (!dialog.Cancelled && dialog.Error != null)
                        {
                            LogDialog.Log("Failed loading URL", dialog.Error);

                            // Check whether or not the URL is valid and show an error message if necessary
                            if (dialog.Error is ArgumentNullException || string.IsNullOrEmpty(expandedUrl))
                            {
                                MessageBox.Show(this, "The URL you entered is empty and cannot be loaded.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else if (dialog.Error is UriFormatException)
                            {
                                MessageBox.Show(this, "The specified URL '" + expandedUrl + "' is not valid.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                MessageBox.Show(this, "The contents of the URL can not be loaded: " + dialog.Error.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }

                    rtfContent.Text = CurrentVariable.TempContent;
                    // For Regex: Go to match after thread finish
                    this.gotoMatch = true;
                    UpdateRegexMatches();
                    // For Start/End: Go to match now
                    RefreshRtfFormatting();

                    this.GoToMatch();

                    // Show page preview if desired
                    if (cmnuBrowser.Checked)
                    {
                        PreviewDialog.ShowPreview(this, expandedUrl, postData);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "An error occured when loading the URL: " + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Exemplo n.º 28
0
        private async void clickBtnRegister(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Email.Text) || string.IsNullOrWhiteSpace(Email.Text))
            {
                displaySnackBar("Fill Email!");
            }
            else if (string.IsNullOrEmpty(Username.Text) || string.IsNullOrWhiteSpace(Username.Text))
            {
                displaySnackBar("Fill username!");
            }
            else if (string.IsNullOrEmpty(Password.Text) || string.IsNullOrWhiteSpace(Password.Text))
            {
                displaySnackBar("Fill password!");
            }
            else if (string.IsNullOrEmpty(ConfirmPassword.Text) || string.IsNullOrWhiteSpace(ConfirmPassword.Text))
            {
                displaySnackBar("Fill column confirm password!");
            }
            else if (string.IsNullOrEmpty(FirstName.Text) || string.IsNullOrWhiteSpace(FirstName.Text))
            {
                displaySnackBar("Fill First name!");
            }
            else if (string.IsNullOrEmpty(LastName.Text) || string.IsNullOrWhiteSpace(LastName.Text))
            {
                displaySnackBar("Fill Last name!");
            }
            else if (Password.Text != ConfirmPassword.Text)
            {
                displaySnackBar("Confirm password do not match with password. Please check them.");
            }
            else
            {
                var progressDialog = new ProgressDialog(this);
                progressDialog.SetCancelable(true);
                progressDialog.SetMessage("Please wait!");
                progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
                progressDialog.Show();

                string email           = Email.Text;
                string username        = Username.Text;
                string password        = Password.Text;
                string confirmPassword = ConfirmPassword.Text;
                string fistName        = FirstName.Text;
                string lastName        = LastName.Text;
                string phoneNumber     = PhoneNumber.Text;

                httpClient = new HttpClient();

                var resultForUsername = await httpClient.PostAsync("UrlApiapi/account/checkUsername", new StringContent(JsonConvert.SerializeObject(username), Encoding.UTF8, "application/json"));

                var responseForUsername = await resultForUsername.Content.ReadAsStringAsync();

                var resultForEmail = await httpClient.PostAsync("UrlApiapi/account/checkEmail", new StringContent(JsonConvert.SerializeObject(email), Encoding.UTF8, "application/json"));

                var responseForEmail = await resultForEmail.Content.ReadAsStringAsync();

                if (responseForUsername == "true")
                {
                    displaySnackBar("There exist user with this username.");
                    progressDialog.Hide();
                }
                else if (responseForEmail == "true")
                {
                    displaySnackBar("There exisit new user with this mail.");
                    progressDialog.Hide();
                }
                else
                {
                    string base64Image = "";
                    try
                    {
                        UserImage.BuildDrawingCache(true);
                        BitmapDrawable bd     = (BitmapDrawable)UserImage.Drawable;
                        Bitmap         bitmap = bd.Bitmap;
                        byte[]         imageData;
                        using (MemoryStream stream = new MemoryStream())
                        {
                            bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
                            imageData = stream.ToArray();
                        }
                        base64Image = Convert.ToBase64String(imageData);
                    }
                    catch (Exception ex) { }

                    try
                    {
                        var signUp = new SignUp
                        {
                            Email           = email,
                            UserName        = username,
                            FirstName       = fistName,
                            LastName        = lastName,
                            BirthDate       = DateTime.Now.ToString(),
                            Password        = password,
                            PhoneNumber     = phoneNumber,
                            user_image      = base64Image,
                            ConfirmPassword = confirmPassword,
                            Gender          = "M"
                        };

                        var httpClient  = new HttpClient();
                        var jsonContent = JsonConvert.SerializeObject(signUp);
                        var content     = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                        var response    = await httpClient.PostAsync("UrlApiapi/account/Register", content);

                        var responseString = await response.Content.ReadAsStringAsync();

                        Toast.MakeText(this, "Check your email for further details.", ToastLength.Long).Show();
                        progressDialog.Cancel();
                        StartActivity(typeof(LogIn));
                    }
                    catch (HttpRequestException httpEx)
                    {
                        Snackbar bar = Snackbar.Make(linearLayout2, "Please check your internet connection!", Snackbar.LengthLong);
                        Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View;
                        layout.SetMinimumHeight(100);
                        layout.SetBackgroundColor(Android.Graphics.Color.White);
                        layout.TextAlignment = TextAlignment.Center;
                        layout.ScrollBarSize = 16;
                        bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red));
                        bar.SetDuration(Snackbar.LengthIndefinite);
                        bar.SetAction("Ok", (v) => { });
                        bar.Show();
                        progressDialog.Cancel();
                    }
                    catch (Exception ex)
                    {
                        progressDialog.Cancel();
                        Toast.MakeText(this, "Error: " + ex, ToastLength.Long).Show();
                    }
                }
            }
        }