Пример #1
0
        async Task GetSendSMSPermissionAsync()
        {
            //Check to see if any permission in our group is available, if one, then all are
            const string permission = Manifest.Permission.SendSms;
            if (CheckSelfPermission(Manifest.Permission.SendSms) == (int)Permission.Granted)
            {
                await SMSSend();
                return;
            }

            //need to request permission
            if (ShouldShowRequestPermissionRationale(permission))
            {
               
                var callDialog = new AlertDialog.Builder(this);
                callDialog.SetTitle("explain");
                callDialog.SetMessage("This app needt to send sms so it need sms send permission");
                callDialog.SetNeutralButton("yes", delegate {
                   RequestPermissions(PermissionsLocation, RequestLocationId);
                });
                callDialog.SetNegativeButton("no", delegate { });
               
                callDialog.Show();
                return;
            }
            //Finally request permissions with the list of permissions and Id
            RequestPermissions(PermissionsLocation, RequestLocationId);
        }
		private static AlertDialogInfo CreateDialog(string content, string title, string okText = null, string cancelText = null, Action<bool> afterHideCallbackWithResponse = null)
		{
			var tcs = new TaskCompletionSource<bool>();
			var builder = new AlertDialog.Builder(AppCompatActivityBase.CurrentActivity);
			builder.SetMessage(content);
			builder.SetTitle(title);
			var dialog = (AlertDialog)null;
			builder.SetPositiveButton(okText ?? "OK", (d, index) =>
				{
					tcs.TrySetResult(true);
					if (dialog != null)
					{
						dialog.Dismiss();
						dialog.Dispose();
					}
					if (afterHideCallbackWithResponse == null)
						return;
					afterHideCallbackWithResponse(true);
				});

			if (cancelText != null)
			{
				builder.SetNegativeButton(cancelText, (d, index) =>
					{
						tcs.TrySetResult(false);
						if (dialog != null)
						{
							dialog.Dismiss();
							dialog.Dispose();
						}
						if (afterHideCallbackWithResponse == null)
							return;
						afterHideCallbackWithResponse(false);
					});
			}

			builder.SetOnDismissListener(new OnDismissListener(() =>
				{
					tcs.TrySetResult(false);
					if (afterHideCallbackWithResponse == null)
						return;
					afterHideCallbackWithResponse(false);
				}));

			dialog = builder.Create();

			return new AlertDialogInfo
			{
				Dialog = dialog,
				Tcs = tcs
			};
		}
Пример #3
0
        /// <summary>
        /// Shows the message box.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="caption">The caption.</param>
        /// <param name="button">The button.</param>
        /// <param name="icon">The icon.</param>
        /// <returns>The message result.</returns>
        /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception>
        protected virtual Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None)
        {
            var messageResult = MessageResult.Cancel;
            var context = Catel.Android.ContextHelper.CurrentContext;
            var builder = new AlertDialog.Builder(context);

            switch (button)
            {
                case MessageButton.OK:
                    builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; });
                    break;

                case MessageButton.OKCancel:
                    builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; });
                    builder.SetCancelable(true);
                    break;

                case MessageButton.YesNo:
                    builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; });
                    builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; });
                    break;

                case MessageButton.YesNoCancel:
                    builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; });
                    builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; });
                    builder.SetCancelable(true);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("button");
            }

            return Task<MessageResult>.Run(() =>
            {
                builder.SetMessage(message).SetTitle(caption);
                builder.Show();

                return messageResult;
            });
        }
Пример #4
0
        public string SendNotification()
        {
            try
            {
                var intent = new Intent(mContext, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                intent.PutExtra("Android Notification", "Notificaiton");
                var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot);

                var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/" + Resource.Attribute.actionBarDivider);
                // Creating an Audio Attribute
                var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Notification).Build();

                mBuilder = new NotificationCompat.Builder(mContext);
                mBuilder.SetSmallIcon(Resource.Drawable.alerticon);
                mBuilder.SetContentTitle("Android Notification")
                .SetSound(sound)
                .SetAutoCancel(true)
                .SetContentTitle("Android Notification")
                .SetContentText("Notificaiton")
                .SetChannelId(NOTIFICATION_CHANNEL_ID)
                .SetPriority((int)NotificationPriority.High)
                .SetVibrate(new long[0])
                .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                .SetVisibility((int)NotificationVisibility.Public)
                .SetSmallIcon(Resource.Drawable.alerticon)
                .SetContentIntent(pendingIntent);



                NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;

                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance = global::Android.App.NotificationImportance.High;

                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notificaiton", importance);
                    notificationChannel.EnableLights(true);
                    notificationChannel.EnableVibration(true);
                    notificationChannel.SetSound(sound, alarmAttributes);
                    notificationChannel.SetShowBadge(true);
                    notificationChannel.Importance = NotificationImportance.High;
                    notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                    if (notificationManager != null)
                    {
                        mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
                        notificationManager.CreateNotificationChannel(notificationChannel);
                    }
                }

                notificationManager.Notify(0, mBuilder.Build());
                //MainActivity.ShowAlert();


                AlertDialog.Builder alertDiag = new AlertDialog.Builder(MainActivity.contextForDialog);
                alertDiag.SetTitle("Notification");
                alertDiag.SetMessage("Notification Generated");

                EditText input = new EditText(MainActivity.contextForDialog);
                // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                input.SetRawInputType(Android.Text.InputTypes.ClassText | Android.Text.InputTypes.NumberVariationPassword);
                alertDiag.SetView(input);

                alertDiag.SetPositiveButton("OK", (senderAlert, args) => {
                    sendValue(input.Text.ToString());

                    //Toast.MakeText(MainActivity.contextForDialog, "Notification Opened", ToastLength.Short).Show();
                });
                alertDiag.SetNegativeButton("Cancel", (senderAlert, args) => {
                    alertDiag.Dispose();
                });
                Dialog diag = alertDiag.Create();
                diag.Show();
            }
            catch (Exception ex)
            {
                //
            }
            return("123321");
        }
 private void ShowMessage(string message, string title)
 {
     // Display the message to the user.
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     builder.SetMessage(message).SetTitle(title).Show();
 }
        void init()
        {
            #region Start
            SetContentView(Resource.Layout.Home);
            try
            {
                this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen);
                ActionBar.Show();
            }catch { }
            Global.SavedMainActivity = this;
            //StartService(new Intent(this, typeof(DemoService)));
            Settings                       = this.GetSharedPreferences(this.PackageName + Global.ApplicationInfo.VersionName + ".Settings", FileCreationMode.MultiProcess);
            SettingsEditor                 = Settings.Edit();
            ActivateButton                 = FindViewById <Switch>(Resource.Id.switch1);
            SpeedTextView                  = FindViewById <TextView>(Resource.Id.textView4);
            StatusTextView                 = FindViewById <TextView>(Resource.Id.textView5);
            SpeedTypeImageView             = FindViewById <ImageView>(Resource.Id.imageView2);
            UploadTypeImageView            = FindViewById <ImageView>(Resource.Id.imageView3);
            LocationTextView               = FindViewById <TextView>(Resource.Id.textView3);
            LocationTextView.TextFormatted = Android.Text.Html.FromHtml("<i>Connecting...</i>");
            #endregion
            #region "Toolbar"
            ActionBar.SetHomeButtonEnabled(false);
            ActionBar.SetDisplayShowHomeEnabled(false);
            ActionBar.SetDisplayUseLogoEnabled(true);
            ActionBar.SetIcon(Resources.GetDrawable(Resource.Drawable.favicon));
            ActionBar.SetLogo(Resources.GetDrawable(Resource.Drawable.favicon));
            ActionBar.TitleFormatted = Android.Text.Html.FromHtml("<font color='#FF8000'>" + this.Title + "</font>");
            ActionBar.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.ParseColor("#1f669b")));
            FindViewById <ImageButton>(Resource.Id.imageButton3).Click += delegate
            {
                StartActivity(new Intent(this, typeof(MapActivity)));
            };
            FindViewById <ImageButton>(Resource.Id.imageButton4).Click += delegate
            {
                var i = new Intent();
                i.SetAction(Intent.ActionView);
                i.SetData(Android.Net.Uri.Parse("http://umwelt.kurzweb.de"));
                StartActivity(i);
            };
            FindViewById <ImageButton>(Resource.Id.imageButton5).Click += delegate
            {
                Upload();
            };
            #endregion
            #region Init
            InitializeLocationManager();
            InizializeMediaRecorder();
            #endregion
            #region Main
            try
            {
                locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);
            }
            catch { }

            double lastLevel;
            timer1          = new System.Timers.Timer();
            timer1.Interval = 100;
            timer1.Enabled  = true;
            timer1.Elapsed += delegate {
                var thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate {
                    try
                    {
                        if (mediaRecorder == null)
                        {
                            InizializeMediaRecorder();
                        }
                        ;
                        var b   = FindViewById <TextView>(Resource.Id.textView1);
                        var a   = FindViewById <ProgressBar>(Resource.Id.progressBar1);
                        var max = mediaRecorder.MaxAmplitude;
                        long db = (long)(10 * System.Math.Round(System.Math.Log(max / 10), 1));//20 * System.Math.Log10(mediaRecorder.MaxAmplitude) - 10 ;//0.00002 2700.0 32767 //-20 * System.Math.Log10(mediaRecorder.MaxAmplitude / 51805.5336 / 0.05)
                        //double db = 20 * System.Math.Log10(mediaRecorder.MaxAmplitude / 32768.0);
                        lastLevel = db;
                        System.Diagnostics.Debug.Print("[----]" + max.ToString() + "=>" + lastLevel.ToString());
                        if (double.IsInfinity(lastLevel))
                        {
                            lastLevel = LevelBefore;
                        }
                        else
                        {
                            LevelBefore = lastLevel;
                        }
                        if (ActivateButton.Checked)
                        {
                            RunOnUiThread(delegate
                            {
                                if (LocationTextView.Text == "Do not track" || LocationTextView.Text == "Connecting...")
                                {
                                    LocationTextView.TextFormatted = Android.Text.Html.FromHtml("<i>Connecting...</i>");
                                    try
                                    {
                                        locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);
                                    }
                                    catch { }
                                }
                                b.Text     = lastLevel.ToString() + "db";
                                _db        = (int)lastLevel;
                                a.Max      = 150;
                                a.Enabled  = false;
                                a.Progress = (int)lastLevel;
                                if ((int)lastLevel <= 75)
                                {
                                    a.ProgressDrawable.SetColorFilter(Android.Graphics.Color.LightGreen, Android.Graphics.PorterDuff.Mode.Multiply);
                                }
                                else if ((int)lastLevel <= 90)
                                {
                                    a.ProgressDrawable.SetColorFilter(Android.Graphics.Color.Yellow, Android.Graphics.PorterDuff.Mode.Multiply);
                                }
                                else if ((int)lastLevel <= 100)
                                {
                                    a.ProgressDrawable.SetColorFilter(Android.Graphics.Color.Orange, Android.Graphics.PorterDuff.Mode.Multiply);
                                }
                                else
                                {
                                    a.ProgressDrawable.SetColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply);
                                }
                            });
                        }
                    }
                    catch (Java.Lang.Exception e)
                    {
                        RunOnUiThread(delegate { Toast.MakeText(this, "Fehler: " + e.Message, ToastLength.Short).Show(); });
                    }
                }));
                thread.IsBackground = true;
                thread.Start();
            };
            timer1.Start();
            timer2          = new System.Timers.Timer();
            timer2.Interval = Settings.GetInt("Hochlade_Interval", 10) * 1000;
            timer2.Elapsed += delegate {
                var thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate {
                    if (Settings.GetBoolean("Automatisch_Hochladen", false) == false)
                    {
                        timer2.Stop(); timer2.Enabled = false; return;
                    }
                    Upload(false);
                }));
                thread.IsBackground = true;
                thread.Start();
            };
            CheckAutoUpdate();
            ActivateButton.CheckedChange += delegate
            {
                if (ActivateButton.Checked)
                {
                    CheckLocationManager();
                    timer1.Start();
                    timer1.Enabled = true;
                    FindViewById <LinearLayout>(Resource.Id.linearLayout1).Visibility = ViewStates.Visible;
                    var ll = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent);
                    ll.AddRule(LayoutRules.Below, Resource.Id.linearLayout1);
                    FindViewById <LinearLayout>(Resource.Id.linearLayout2).LayoutParameters = ll;
                    CheckAutoUpdate();
                }
                else
                {
                    timer1.Stop();
                    timer1.Enabled = false;
                    FindViewById <LinearLayout>(Resource.Id.linearLayout1).Visibility = ViewStates.Gone;
                    var ll = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent);
                    ll.AddRule(LayoutRules.Below, Resource.Id.LL1);
                    //ll.SetMargins(0, -100, 0, 0);
                    FindViewById <LinearLayout>(Resource.Id.linearLayout2).LayoutParameters = ll;
                    LocationTextView.TextFormatted = Android.Text.Html.FromHtml("<i>Do not track</i>");
                    var a = FindViewById <ProgressBar>(Resource.Id.progressBar1);
                    var b = FindViewById <TextView>(Resource.Id.textView1);
                    StatusTextView.TextFormatted = Android.Text.Html.FromHtml("<i>Messen deaktiviert</i>");
                    UploadTypeImageView.SetImageResource(Resource.Drawable.pause);
                    a.Progress = 0;
                    b.Text     = "--";
                    a.ProgressDrawable.SetColorFilter(Android.Graphics.Color.Gray, Android.Graphics.PorterDuff.Mode.Multiply);
                    try
                    {
                        locationManager.RemoveUpdates(this);
                    }catch { }
                }
            };
            splashscreen = false;
            CheckLocationManager();
            #endregion
            #region Update
            if (NewVersion)
            {
                var dialog = new AlertDialog.Builder(this);
                dialog.SetTitle("Neues Update");
                dialog.SetMessage("Wollen Sie jetzt die auf die neue Version updaten?!");
                dialog.SetPositiveButton("Update", delegate {
                    var a = new WebClient();
                    a.DownloadFileCompleted += A_DownloadFileCompleted;
                    Functions.CheckDirectory();
                    try
                    {
                        a.DownloadFileAsync(new Uri("http://kurzweb.de/umwelt/app/" + NewVersionName + ".apk"), Global.HomeDirectory + "Update_" + NewVersionName + ".apk");
                    }
                    catch (Exception ex) {
                        Functions.ShowError(this, ex, "Das Update konnte nicht heruntergeladen werden");
                    }
                });
                dialog.SetNegativeButton("Später", delegate { });
                dialog.SetIcon(Resources.GetDrawable(Resource.Drawable.update));
                dialog.Show();
            }
            #endregion
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.RegisterScreen);

            TextView title                 = FindViewById <TextView> (Resource.Id.registerHeading);
            EditText studentIDInput        = FindViewById <EditText> (Resource.Id.registerStudentIDInput);
            EditText passwordInput         = FindViewById <EditText> (Resource.Id.registerPasswordInput);
            EditText rePasswordInput       = FindViewById <EditText> (Resource.Id.registerRePasswordInput);
            EditText nameInput             = FindViewById <EditText> (Resource.Id.registerStudentNameInput);
            EditText nationalityInput      = FindViewById <EditText> (Resource.Id.registerNationalityInput);
            Spinner  basicInterest         = FindViewById <Spinner> (Resource.Id.registerInterest);
            CheckBox agreeTac              = FindViewById <CheckBox> (Resource.Id.registerAgreeTac);
            Button   registerAccountButton = FindViewById <Button> (Resource.Id.registerAccountButton);
            Button   cancelButton          = FindViewById <Button> (Resource.Id.cancelButton);

            // Set up fonts.
            Typeface din     = Typeface.CreateFromAsset(this.Assets, "fonts/din-regular.ttf");
            Typeface dinBold = Typeface.CreateFromAsset(this.Assets, "fonts/din-bold.ttf");

            // Set font to "Din".
            agreeTac.SetTypeface(din, TypefaceStyle.Normal);

            // Set font to "Din Bold".
            title.SetTypeface(dinBold, TypefaceStyle.Normal);
            registerAccountButton.SetTypeface(dinBold, TypefaceStyle.Normal);
            cancelButton.SetTypeface(dinBold, TypefaceStyle.Normal);

            string studentID   = String.Empty;
            string password    = String.Empty;
            string rePassword  = String.Empty;
            string name        = String.Empty;
            string nationality = String.Empty;
            bool   tac         = false;

            string path      = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var    accountDB = new SQLiteConnection(System.IO.Path.Combine(path, "Database.db"));

            registerAccountButton.Click += (object sender, EventArgs e) => {
                studentID   = studentIDInput.Text;
                password    = passwordInput.Text;
                rePassword  = rePasswordInput.Text;
                name        = nameInput.Text;
                nationality = nationalityInput.Text;
                tac         = agreeTac.Checked;

                string[] input = { studentID, password, rePassword, name, nationality };

                if (InputValidation.isFilled(input))
                {
                    string message = "";
                    var    result  = accountDB.Query <Account>("SELECT * FROM Account WHERE StudentID = '" + studentID + "'");

                    if (result.Count != 0)
                    {
                        message = GetString(Resource.String.account_exists);
                        DisplayUnsuccessfulAlert(message);
                    }

                    else if (!password.Equals(rePassword))
                    {
                        message = GetString(Resource.String.mismatched_passwords);
                        DisplayUnsuccessfulAlert(message);
                    }

                    else if (basicInterest.SelectedItem.ToString() == "Please select an interest...")
                    {
                        message = GetString(Resource.String.select_interest);
                        DisplayUnsuccessfulAlert(message);
                    }

                    else if (!tac)
                    {
                        message = GetString(Resource.String.must_agree);
                        DisplayUnsuccessfulAlert(message);
                    }

                    else
                    {
                        Account       acc       = new Account();
                        Profile       prof      = new Profile();
                        Accommodation accom     = new Accommodation();
                        var           accomList = accountDB.Query <Account> ("SELECT * FROM Accommodation");

                        acc.StudentID = studentID;
                        acc.Password  = password;
                        accountDB.Insert(acc);

                        prof.StudentID       = studentID;
                        prof.StudentName     = name;
                        prof.Nationality     = nationality;
                        prof.ContactNumber   = String.Empty;
                        prof.Degree          = String.Empty;
                        prof.Interest        = basicInterest.SelectedItem.ToString();
                        prof.Year            = String.Empty;
                        prof.AccommodationID = accomList.Count.ToString();
                        accountDB.Insert(prof);

                        accom.ID               = accomList.Count.ToString();
                        accom.Address          = String.Empty;
                        accom.Suburb           = String.Empty;
                        accom.RentAWeek        = String.Empty;
                        accom.PreferredContact = String.Empty;
                        accom.Description      = String.Empty;
                        accountDB.Insert(accom);

                        var successfulAlert = new AlertDialog.Builder(this);

                        successfulAlert.SetMessage(GetString(Resource.String.account_created));
                        successfulAlert.SetNeutralButton("OK", delegate {
                            var intent = new Intent(this, typeof(MainActivity));
                            StartActivity(intent);
                            // Stops user from pressing back button to return.
                            Finish();
                        });
                        successfulAlert.Show();
                    }
                }
                else
                {
                    var notFilledAlert = new AlertDialog.Builder(this);

                    notFilledAlert.SetMessage(GetString(Resource.String.required_fields));
                    notFilledAlert.SetNegativeButton("OK", delegate {});
                    notFilledAlert.Show();
                }
            };

            cancelButton.Click += (object sender, EventArgs e) => {
                var intent = new Intent(this, typeof(MainActivity));
                StartActivity(intent);
            };
        }
Пример #8
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AlterarSituacaoOpr);


            var db = new SQLiteAsyncConnection(dbPath);
            var dadosConfiguracao = db.Table <Configuracao>();
            var dadosToken        = db.Table <Token>();
            var configuracao      = await dadosConfiguracao.FirstOrDefaultAsync();

            var TokenAtual = await dadosToken.Where(x => x.data_att_token >= DateTime.Now).FirstOrDefaultAsync();

            string url = "http://" + configuracao.endereco + "/Api/GerenciamentoPatio/GetCesvNumero?Numero=" + TokenAtual.numeroCesv + "&ArmazemId=" + TokenAtual.armazemId + "&UsuarioCod=" + TokenAtual.loginId;

            System.Uri     myUri        = new System.Uri(url);
            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);

            var myHttpWebRequest = (HttpWebRequest)myWebRequest;

            myHttpWebRequest.PreAuthenticate = true;
            myHttpWebRequest.Headers.Add("Authorization", "Bearer " + TokenAtual.access_token);
            myHttpWebRequest.Accept = "application/json";

            var myWebResponse  = myWebRequest.GetResponse();
            var responseStream = myWebResponse.GetResponseStream();

            var myStreamReader = new StreamReader(responseStream, Encoding.Default);
            var json           = myStreamReader.ReadToEnd();

            responseStream.Close();
            myWebResponse.Close();

            var DadosRelatorioCesv = JsonConvert.DeserializeObject <ModelCesv>(json);

            if (string.IsNullOrEmpty(DadosRelatorioCesv.msg))
            {
                RelatorioCesv.Add(string.Concat("Numero: ", DadosRelatorioCesv.numero));
                RelatorioCesv.Add(string.Concat("Placa: ", DadosRelatorioCesv.placa.ToUpper()));
                RelatorioCesv.Add(string.Concat("Status: ", DadosRelatorioCesv.statusInicio));
                RelatorioCesv.Add(string.Concat("Motorista: ", DadosRelatorioCesv.nome));
                RelatorioCesv.Add(string.Concat("Telefone: ", DadosRelatorioCesv.telefone));
                RelatorioCesv.Add(string.Concat("Cliente: ", DadosRelatorioCesv.nomeCliente));
                RelatorioCesv.Add(string.Concat("Transportadora: ", DadosRelatorioCesv.nomeTransportadora));
                RelatorioCesv.Add(string.Concat("Tipo do veículo: ", DadosRelatorioCesv.tipoVeiculo));
                RelatorioCesv.Add(string.Concat("Hora início: ", DadosRelatorioCesv.DataInicioAgendamentoPatio));
                RelatorioCesv.Add(string.Concat("Hora fim: ", DadosRelatorioCesv.DataFimAgendamentoPatio));



                LinearLayout.LayoutParams LayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent)
                {
                    //LayoutParams.Height = LinearLayout.LayoutParams.MatchParent;
                    //LayoutParams.Width = LinearLayout.LayoutParams.MatchParent;
                    Weight = 1
                };
                LayoutParams.SetMargins(10, 3, 10, 0);
                //LinearLayoutParams.Weight = Convert.ToSingle(0.5);


                var scrollView = new ScrollView(this)
                {
                    LayoutParameters = LayoutParams
                };

                this.SetContentView(scrollView);


                var mainLayout = new LinearLayout(this)
                {
                    Orientation      = Orientation.Vertical,
                    WeightSum        = 2,
                    LayoutParameters = LayoutParams
                };

                scrollView.AddView(mainLayout);

                var texto1 = new TextView(this)
                {
                    Text             = string.Concat("Numero: ", DadosRelatorioCesv.numero),
                    LayoutParameters = LayoutParams
                };
                texto1.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto1);

                var texto2 = new TextView(this)
                {
                    Text             = string.Concat("Placa: ", DadosRelatorioCesv.placa),
                    LayoutParameters = LayoutParams
                };
                texto2.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto2);

                var texto3 = new TextView(this)
                {
                    Text             = string.Concat("Cliente: ", DadosRelatorioCesv.nomeCliente),
                    LayoutParameters = LayoutParams
                };
                texto3.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto3);

                var texto4 = new TextView(this)
                {
                    Text             = string.Concat("Transportadora: ", DadosRelatorioCesv.nomeTransportadora),
                    LayoutParameters = LayoutParams
                };
                texto4.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto4);

                var texto5 = new TextView(this)
                {
                    Text             = string.Concat("Motorista: ", DadosRelatorioCesv.nome),
                    LayoutParameters = LayoutParams
                };
                texto5.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto5);

                var texto6 = new TextView(this)
                {
                    Text             = string.Concat("Status: ", DadosRelatorioCesv.statusInicio),
                    LayoutParameters = LayoutParams
                };
                texto6.SetTextSize(ComplexUnitType.Sp, 15);
                mainLayout.AddView(texto6);



                for (int n = 0; n < DadosRelatorioCesv.ListaDestinos.Count; n++)
                {
                    var aButton = new Button(this)
                    {
                        LayoutParameters = LayoutParams
                    };
                    //aButton.SetBackgroundResource(Color.Rgb(10 ,10 ,10));
                    //aButton.DrawingCacheBackgroundColor = Color.ParseColor("#FF6A00");
                    aButton.SetBackgroundColor(Color.ParseColor(DadosRelatorioCesv.ListaDestinos[n].cor));
                    aButton.SetTextColor(Color.ParseColor("#ffffff"));

                    //aButton.;
                    //aButton.SetTextColor(GetColor(Resource.Color.blue_agend));
                    //aButton.SetTextColor(new r.ColorStateList(new int[][] { new int[] { } }, new int[] { Color.White.ToArgb() }));
                    aButton.Id   = Convert.ToInt32(DadosRelatorioCesv.ListaDestinos[n].statusId);
                    aButton.Text = DadosRelatorioCesv.ListaDestinos[n].denominacao;
                    aButton.SetTextSize(ComplexUnitType.Sp, 50);
                    aButton.Click += delegate(object sender, EventArgs e)
                    {
                        AlertDialog.Builder alert = new AlertDialog.Builder(this);
                        alert.SetTitle("Confirma a alteração da situação da CESV ?");
                        alert.SetPositiveButton("Confirma", (senderAlert, args) => {
                            string indice = (sender as Button).Id.ToString();

                            string urlPost                  = "http://" + configuracao.endereco + "/Api/GerenciamentoPatio/PostCesvAlteracaoStatus?CesvId=" + DadosRelatorioCesv.cesvId + "&StatusOrigemId=" + DadosRelatorioCesv.statusInicioId + "&StatusDestinoId=" + indice + "&UsuarioCod=" + TokenAtual.loginId;
                            System.Uri myUriPost            = new System.Uri(urlPost);
                            HttpWebRequest myWebRequestPost = (HttpWebRequest)HttpWebRequest.Create(myUriPost);

                            var myHttpWebRequestPost             = (HttpWebRequest)myWebRequestPost;
                            myHttpWebRequestPost.PreAuthenticate = true;
                            myHttpWebRequestPost.Method          = "POST";
                            myHttpWebRequestPost.ContentLength   = 0;
                            myHttpWebRequestPost.Headers.Add("Authorization", "Bearer " + TokenAtual.access_token);
                            myHttpWebRequestPost.Accept = "application/json";

                            var myWebResponsePost  = myWebRequestPost.GetResponse();
                            var responseStreamPost = myWebResponsePost.GetResponseStream();

                            var myStreamReaderPost = new StreamReader(responseStreamPost, Encoding.Default);
                            var jsonPost           = myStreamReaderPost.ReadToEnd();

                            responseStreamPost.Close();
                            myWebResponsePost.Close();
                            Toast.MakeText(Application, "Cesv alterada com sucesso!", ToastLength.Long).Show();
                            StartActivity(typeof(LoginActivity));
                            Finish();
                        });

                        alert.SetNegativeButton("Cancela", (senderAlert, args) => {
                            //Toast.MakeText(Activity, "Cancelado!", ToastLength.Short).Show();
                        });

                        Dialog dialog = alert.Create();
                        dialog.Show();
                    };
                    mainLayout.AddView(aButton);
                }
            }
            else
            {
                Toast.MakeText(Application, DadosRelatorioCesv.msg, ToastLength.Long).Show();
                Finish();
            }
        }
Пример #9
0
        private void Popup_MenuItemClick(object sender, PopupMenu.MenuItemClickEventArgs e)
        {
            switch (e.Item.ItemId)
            {
            case Resource.Id.selectMember:
                int             rownum = option;
                DataTable       data   = new DataTable();
                MySqlConnection conn   = new MySqlConnection("server=db4free.net;port=3307;database=teamhubunibuc;user id=teamhubunibuc;password=teamhubunibuc;charset=utf8");
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                    MySqlCommand     getMember = new MySqlCommand("SELECT id_member FROM THMembers_on_teams WHERE id_team = " + Fragment_projects.idTeamSelected + " ;", conn);
                    MySqlDataAdapter adapter   = new MySqlDataAdapter(getMember);
                    adapter.Fill(data);
                    foreach (DataRow row in data.Rows)
                    {
                        if (rownum == 0)
                        {
                            idMemberSelected = System.Convert.ToInt32(row["id_member"].ToString());
                            AlertDialog.Builder alertDelSucces = new AlertDialog.Builder(this.Activity);
                            alertDelSucces.SetMessage("You have selected a member !");
                            alertDelSucces.Show();
                            break;
                        }
                        else
                        {
                            rownum--;
                        }
                    }
                    conn.Close();
                }
                break;

            case Resource.Id.deleteMember:
                int             rownumDel = option;
                DataTable       dataDel   = new DataTable();
                MySqlConnection connDel   = new MySqlConnection("server=db4free.net;port=3307;database=teamhubunibuc;user id=teamhubunibuc;password=teamhubunibuc;charset=utf8");
                if (connDel.State == ConnectionState.Closed)
                {
                    connDel.Open();
                    MySqlCommand     getMember = new MySqlCommand("SELECT id_member FROM THMembers_on_teams WHERE id_team = " + Fragment_projects.idTeamSelected + " ;", connDel);
                    MySqlDataAdapter adapter   = new MySqlDataAdapter(getMember);
                    adapter.Fill(dataDel);
                    foreach (DataRow row in dataDel.Rows)
                    {
                        if (rownumDel == 0)
                        {
                            idMemberSelected = System.Convert.ToInt32(row["id_member"].ToString());
                            break;
                        }
                        else
                        {
                            rownumDel--;
                        }
                    }
                    if (idMemberSelected != MainActivity.user_id)
                    {
                        MySqlCommand delMemberFromMonT = new MySqlCommand("DELETE FROM THMembers_on_teams where id_member =" + idMemberSelected + ";", connDel);
                        delMemberFromMonT.ExecuteNonQuery();
                        AlertDialog.Builder alertDelSucces = new AlertDialog.Builder(this.Activity);
                        alertDelSucces.SetMessage("The member has been succesfully deleted !");
                        alertDelSucces.Show();
                    }
                    else
                    {
                        AlertDialog.Builder alertDelError = new AlertDialog.Builder(this.Activity);
                        alertDelError.SetMessage("You can not delete this member !");
                        alertDelError.Show();
                    }
                    connDel.Close();
                }
                break;

            default: throw new NotImplementedException();
            }
        }
Пример #10
0
        private async void BtnLogIN_Click(object sender, EventArgs e)
        {
            InputMethodManager inputManager = (InputMethodManager)this.GetSystemService(Context.InputMethodService);

            inputManager.HideSoftInputFromWindow(this.CurrentFocus.WindowToken, HideSoftInputFlags.NotAlways);

            try
            {
                Drawable icon_error = Resources.GetDrawable(Resource.Drawable.alert);
                icon_error.SetBounds(0, 0, 40, 30);
                if (txt_UserName.Text != "")
                {
                    if (txt_Password.Text != "")
                    {
                        UserLoginModel _objUserLoginModel = new UserLoginModel();
                        StatusModel.UserTokenNo        = Convert.ToInt32(txt_UserName.Text.Trim());
                        _objUserLoginModel.UserTokenNo = Convert.ToInt32(txt_UserName.Text.Trim());
                        _objUserLoginModel.Password    = txt_Password.Text.Trim();

                        string Url = StatusModel.Url + "UserLogIn";

                        progressDialog = ProgressDialog.Show(this, Android.Text.Html.FromHtml("<font color='#EC407A'> Please wait...</font>"), Android.Text.Html.FromHtml("<font color='#EC407A'> Checking User Info...</font>"), true);

                        var PostString  = JsonConvert.SerializeObject(_objUserLoginModel);
                        var requestTemp = await _objHelper.MakePostRequest(Url, PostString, true);

                        ResponseMessege ResultgetRequest = JsonConvert.DeserializeObject <ResponseMessege>(requestTemp);

                        if (ResultgetRequest.success == 1)
                        {
                            clear();
                            progressDialog.Hide();
                            AlertDialog.Builder alert = new AlertDialog.Builder(this);
                            alert.SetTitle("PaperLess PDI Says:");
                            alert.SetMessage(ResultgetRequest.msg.ToString());
                            alert.SetNeutralButton("OK", (senderAlert, args) =>
                            {
                                Intent intent = new Intent(this, typeof(HomeActivity));
                                this.StartActivity(intent);
                            });

                            Dialog dialog = alert.Create();
                            dialog.Show();
                            clear();
                            return;
                        }

                        else
                        {
                            progressDialog.Hide();
                            AlertDialog.Builder alert = new AlertDialog.Builder(this);
                            alert.SetTitle("PaperLess PDI Says:");
                            alert.SetMessage(ResultgetRequest.msg.ToString());
                            alert.SetNeutralButton("OK", (senderAlert, args) =>
                            {
                            });

                            Dialog dialog = alert.Create();
                            dialog.Show();
                            clear();
                            return;
                        }
                    }
                    else
                    {
                        txt_Password.RequestFocus();
                        txt_Password.SetError("Please Enter Password First", icon_error);
                    }
                }
                else
                {
                    txt_UserName.RequestFocus();
                    txt_UserName.SetError("Please Enter UserName First", icon_error);
                }
            }
            catch (Exception ex)
            {
                progressDialog.Hide();
                string ErrorMsg           = ex.ToString();
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("PaperLess PDI Says:");
                alert.SetMessage(ex.ToString());
                alert.SetNeutralButton("OK", (senderAlert, args) =>
                {
                });

                Dialog dialog = alert.Create();
                dialog.Show();
            }
        }
			public virtual void onFileActionTransferRequested(int id, string path)
			{
				outerInstance.mFilePath = path;
				outerInstance.mTransId = id;
				runOnUiThread(() =>
				{
					AlertDialog.Builder alertbox = new AlertDialog.Builder(outerInstance);
					alertbox.Message = "Do you want to receive file: " + outerInstance.mFilePath + " ?";
					alertbox.setPositiveButton("Accept", new OnClickListenerAnonymousInnerClassHelper(this));
					alertbox.setNegativeButton("Reject", new OnClickListenerAnonymousInnerClassHelper2(this));
					alertbox.Cancelable = false;
					outerInstance.mAlert = alertbox.create();
					outerInstance.mAlert.show();
				});
			}
Пример #12
0
			public virtual Dialog onCreateDialog(Bundle savedInstanceState)
			{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String[] items = new String[files.length];
				string[] items = new string[files.Length];
				for (int i = 0; i < items.Length; i++)
				{
					items[i] = files[i].AbsolutePath;
				}

				AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
				builder.setTitle("PrintPdfFiles").setItems(items, new OnClickListenerAnonymousInnerClassHelper(this, items));
				return builder.create();
			};
Пример #13
0
        protected override void OnCreate(Bundle bundle)
        {
            Stopwatch st = new Stopwatch();

            st.Start();
            base.OnCreate(bundle);
            try
            {
                //SetContentView(Resource.Layout.MyFavoriteGridView);
                ActionBar.SetHomeButtonEnabled(true);
                ActionBar.SetDisplayHomeAsUpEnabled(true);
                if (StoreName == "")
                {
                    StoreName = Intent.GetStringExtra("MyData");
                }
                this.Title = StoreName;
                int              userId = Convert.ToInt32(CurrentUser.getUserId());
                ServiceWrapper   sw     = new ServiceWrapper();
                ItemListResponse output = new ItemListResponse();
                output = sw.GetItemFavsUID(userId).Result;
                List <Item> myArr;
                myArr = output.ItemList.ToList();
                if (output.ItemList.Count == 0)
                {
                    SetContentView(Resource.Layout.FavEmp);
                    TextView  txtName = FindViewById <TextView>(Resource.Id.textView1);
                    ImageView Imag    = FindViewById <ImageView>(Resource.Id.imageView1);
                    //AlertDialog.Builder aler = new AlertDialog.Builder(this, Resource.Style.MyDialogTheme);
                    ////aler.SetTitle("No Reviews Avalilable");
                    //aler.SetMessage("Sorry you didn't tell us your Favourite wines");
                    //LoggingClass.LogInfo("Sorry you didn't tell us your Favourite wines", screenid);
                    //aler.SetNegativeButton("Ok", delegate { Finish(); });
                    //LoggingClass.LogInfo("Clicked on Secaucus", screenid);
                    //Dialog dialog = aler.Create();
                    //dialog.Show();
                }
                else
                {
                    SetContentView(Resource.Layout.MyFavoriteGridView);
                    var gridview = FindViewById <GridView>(Resource.Id.gridviewfav);
                    MyFavoriteAdapter adapter = new MyFavoriteAdapter(this, myArr);
                    LoggingClass.LogInfo("Entered into Favourite Adapter", screenid);
                    gridview.SetNumColumns(2);
                    gridview.Adapter    = adapter;
                    gridview.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args)
                    {
                        try
                        {
                            string WineBarcode = myArr[args.Position].Barcode;
                            int    storeid     = 1;// myArr[args.Position].PlantFinal;
                            //ProgressIndicator.Show(this);
                            AndHUD.Shared.Show(this, "Loading...", Convert.ToInt32(MaskType.Clear));
                            var intent = new Intent(this, typeof(DetailViewActivity));
                            LoggingClass.LogInfo("Clicked on " + myArr[args.Position].Barcode + " to enter into wine details", screenid);
                            intent.PutExtra("WineBarcode", WineBarcode);
                            intent.PutExtra("storeid", storeid);
                            StartActivity(intent);
                        }
                        catch (Exception)
                        {
                            string WineBarcode = myArr[args.Position].Barcode;
                            int    storeid     = myArr[args.Position].PlantFinal;
                            ProgressIndicator.Show(this);
                            AndHUD.Shared.Dismiss();
                            var intent = new Intent(this, typeof(DetailViewActivity));
                            LoggingClass.LogInfo("Clicked on " + myArr[args.Position].Barcode + " to enter into wine details", screenid);
                            intent.PutExtra("WineBarcode", WineBarcode);
                            intent.PutExtra("storeid", storeid);
                            StartActivity(intent);
                        }
                    };

                    LoggingClass.LogInfo("Entered into My Favorites Activity", screenid);
                }
                st.Stop();
                LoggingClass.LogTime("Favouriteactivity", st.Elapsed.TotalSeconds.ToString());
                ProgressIndicator.Hide();
            }

            catch (Exception exe)
            {
                LoggingClass.LogError(exe.Message, screenid, exe.StackTrace.ToString());
                ProgressIndicator.Hide();
                AlertDialog.Builder aler = new AlertDialog.Builder(this);
                aler.SetTitle("Sorry");
                aler.SetMessage("We're under maintainence");
                aler.SetNegativeButton("Ok", delegate { });
                Dialog dialog = aler.Create();
                dialog.Show();
            }
        }
Пример #14
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: private void invokeInstallOption(final int msgID, String msg)
		private void invokeInstallOption(int msgID, string msg)
		{

			DialogInterface.OnClickListener msgClick = new OnClickListenerAnonymousInnerClassHelper(this, msgID);

			AlertDialog.Builder message = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK);

			if (msgID != -1)
			{
				message.Message = msgID;
			}

			if (msg != null)
			{
				message.Message = msg;
			}

			message.setPositiveButton([email protected]_str, msgClick);
			message.Cancelable = false;

			message.show();

		}
Пример #15
0
 void DisplayMessageBox( string title, string message, Note.MessageBoxResult onResult )
 {
     Rock.Mobile.Threading.Util.PerformOnUIThread( delegate
         {
             AlertDialog.Builder dlgAlert = new AlertDialog.Builder( Rock.Mobile.PlatformSpecific.Android.Core.Context );
             dlgAlert.SetTitle( title );
             dlgAlert.SetMessage( message );
             dlgAlert.SetNeutralButton( GeneralStrings.Yes, delegate
                 {
                     onResult( 0 );
                 });
             dlgAlert.SetPositiveButton( GeneralStrings.No, delegate(object sender, DialogClickEventArgs ev )
                 {
                     onResult( 1 );
                 } );
             dlgAlert.Create( ).Show( );
         } );
 }
Пример #16
0
			public OnClickListenerAnonymousInnerClassHelper2(Sample_DOF outerInstance, AlertDialog.Builder dialog)
			{
				this.outerInstance = outerInstance;
				this.dialog = dialog;
			}
Пример #17
0
		/// <summary>
		/// Shows depth of field result into dialog.
		/// </summary>
		private void showResultDialog(params object[] args)
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);

			View dialogView = LayoutInflater.inflate(R.layout.result_dialog_dof, null);

			ImageView autoFocusImage = (ImageView)dialogView.findViewById(R.id.autoFocusImage);
			autoFocusImage.ImageBitmap = (Bitmap)args[0];

			ImageView infinityFocusImage = (ImageView)dialogView.findViewById(R.id.infinityFocusImage);
			infinityFocusImage.ImageBitmap = (Bitmap)args[1];

			ImageView resultImage = (ImageView) dialogView.findViewById(R.id.resultDOFImage);
			resultImage.ImageBitmap = (Bitmap)args[2];

			dialog.setView(dialogView).setTitle("Capture result").setPositiveButton([email protected], new OnClickListenerAnonymousInnerClassHelper2(this, dialog));

			runOnUiThread(() =>
			{
				dialog.show();
			});
		}
Пример #18
0
		/// <summary>
		/// Shows the camera device information into dialog.
		/// </summary>
		private void showInformationDialog()
		{

			StringBuilder builder = new StringBuilder();

			builder.Append("<html><body><pre>");
			if (mCharacteristics != null)
			{
				builder.Append(string.Format("Camera Id: {0}\n", mCameraId));

				// Check supported hardware level.
				SparseArray<string> level = new SparseArray<string>();
				level.put(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL, "Full");
				level.put(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED, "Limited");
				level.put(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY, "Legacy");

				builder.Append(string.Format("Supported H/W Level: {0}\n", level.get(mCharacteristics.get(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL))));

				// Available characteristics tag.
				builder.Append("\nCharacteristics [\n");
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: for(com.samsung.android.sdk.camera.SCameraCharacteristics.Key<?> key : mCharacteristics.getKeys())
				foreach (SCameraCharacteristics.Key<?> key in mCharacteristics.Keys)
				{
					if (mCharacteristics.get(key) is int[])
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.ToString((int[])mCharacteristics.get(key))));
					}
					else if (mCharacteristics.get(key) is Range[])
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.deepToString((Range[])mCharacteristics.get(key))));
					}
					else if (mCharacteristics.get(key) is Size[])
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.deepToString((Size[]) mCharacteristics.get(key))));
					}
					else if (mCharacteristics.get(key) is float[])
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.ToString((float[])mCharacteristics.get(key))));
					}
					else if (mCharacteristics.get(key) is StreamConfigurationMap)
					{
						builder.Append(string.Format("\t{0} --> [\n", key.Name));
						{
							StreamConfigurationMap streamConfigurationMap = mCharacteristics.get(SCameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
							SparseArray<string> formatMap = new SparseArray<string>();
							formatMap.put(ImageFormat.JPEG, "JPEG");
							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
							{
								formatMap.put(ImageFormat.PRIVATE, "PRIVATE");
								formatMap.put(ImageFormat.DEPTH16, "DEPTH16");
								formatMap.put(ImageFormat.DEPTH_POINT_CLOUD, "DEPTH_POINT_CLOUD");
							}
							formatMap.put(ImageFormat.NV16, "NV16");
							formatMap.put(ImageFormat.NV21, "NV21");
							formatMap.put(ImageFormat.RAW10, "RAW10");
							formatMap.put(ImageFormat.RAW_SENSOR, "RAW_SENSOR");
							formatMap.put(ImageFormat.RGB_565, "RGB_565");
							formatMap.put(ImageFormat.UNKNOWN, "UNKNOWN");
							formatMap.put(ImageFormat.YUV_420_888, "420_888");
							formatMap.put(ImageFormat.YUY2, "YUY2");
							formatMap.put(ImageFormat.YV12, "YV12");
							formatMap.put(PixelFormat.RGBA_8888, "RGBA_8888");

							foreach (int format in streamConfigurationMap.OutputFormats)
							{
								builder.Append(string.Format("\t\t{0}(0x{1:x}) --> {2}\n", formatMap.get(format), format, Arrays.deepToString(streamConfigurationMap.getOutputSizes(format))));
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
								{
									builder.Append(string.Format("\t\tHigh Resolution {0}(0x{1:x}) --> {2}\n", formatMap.get(format), format, Arrays.deepToString(streamConfigurationMap.getHighResolutionOutputSizes(format))));
								}
							}

							builder.Append(string.Format("\n\t\tHigh speed video fps --> {0}\n", Arrays.deepToString(streamConfigurationMap.HighSpeedVideoFpsRanges)));
							builder.Append(string.Format("\t\tHigh speed video size --> {0}\n", Arrays.deepToString(streamConfigurationMap.HighSpeedVideoSizes)));

							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
							{
								builder.Append(string.Format("\n\t\tInput formats [\n"));
								foreach (int format in streamConfigurationMap.InputFormats)
								{
									builder.Append(string.Format("\t\t\t{0}(0x{1:x}) --> {2}\n", formatMap.get(format), format, Arrays.deepToString(streamConfigurationMap.getInputSizes(format))));
								}
							}

							builder.Append(string.Format("\t\t]\n"));

						}
						builder.Append("\t]\n");
					}
					else if (mCharacteristics.get(key) is BlackLevelPattern)
					{
						BlackLevelPattern pattern = mCharacteristics.get(SCameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN);
						int[] patternArray = new int[BlackLevelPattern.COUNT];
						pattern.copyTo(patternArray, 0);

						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.ToString(patternArray)));
					}
					else if (mCharacteristics.get(key) is bool[])
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, Arrays.ToString((bool[])mCharacteristics.get(key))));
					}
					else
					{
						builder.Append(string.Format("\t{0} --> {1}\n", key.Name, mCharacteristics.get(key).ToString()));
					}
				}
				builder.Append("]\n");

				// Available characteristics tag.
				builder.Append("\nAvailable characteristics keys [\n");
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: for(com.samsung.android.sdk.camera.SCameraCharacteristics.Key<?> key : mCharacteristics.getKeys())
				foreach (SCameraCharacteristics.Key<?> key in mCharacteristics.Keys)
				{
					builder.Append(string.Format("\t{0}\n", key.Name));
				}
				builder.Append("]\n");

				// Available request tag.
				builder.Append("\nAvailable request keys [\n");
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: for(com.samsung.android.sdk.camera.SCaptureRequest.Key<?> key : mCharacteristics.getAvailableCaptureRequestKeys())
				foreach (SCaptureRequest.Key<?> key in mCharacteristics.AvailableCaptureRequestKeys)
				{
					builder.Append(string.Format("\t{0}\n", key.Name));
				}
				builder.Append("]\n");

				// Available result tag.
				builder.Append("\nAvailable result keys [\n");
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: for(com.samsung.android.sdk.camera.SCaptureResult.Key<?> key : mCharacteristics.getAvailableCaptureResultKeys())
				foreach (SCaptureResult.Key<?> key in mCharacteristics.AvailableCaptureResultKeys)
				{
					builder.Append(string.Format("\t{0}\n", key.Name));
				}
				builder.Append("]\n");

				// Available capability.
				builder.Append("\nAvailable capabilities [\n");
				SparseArray<string> capabilityName = new SparseArray<string>();
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE, "BACKWARD_COMPATIBLE");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR, "MANUAL_SENSOR");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING, "MANUAL_POST_PROCESSING");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW, "RAW");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS, "READ_SENSOR_SETTINGS");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE, "BURST_CAPTURE");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_DEPTH_OUTPUT, "DEPTH_OUTPUT");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING, "PRIVATE_REPROCESSING");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING, "YUV_REPROCESSING");
				capabilityName.put(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO, "HIGH_SPEED_VIDEO");

				foreach (int value in mCharacteristics.get(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES))
				{
					builder.Append(string.Format("\t{0}\n", capabilityName.get(value)));
				}
				builder.Append("]\n");

				{
					builder.Append("\nSamsung extend tags\n");

					// RT-HDR.
					if (mCharacteristics.Keys.contains(SCameraCharacteristics.LIVE_HDR_INFO_LEVEL_RANGE))
					{
						builder.Append(string.Format("\tRT-HDR: {0}\n", mCharacteristics.get(SCameraCharacteristics.LIVE_HDR_INFO_LEVEL_RANGE).ToString()));
					}
					else
					{
						builder.Append("\tRT-HDR: not available\n");
					}

					// Metering mode.
					builder.Append("\tAvailable Metering mode: [\n");
					if (mCharacteristics.Keys.contains(SCameraCharacteristics.METERING_AVAILABLE_MODES))
					{
						SparseArray<string> stringMap = new SparseArray<string>();
						stringMap.put(SCameraCharacteristics.METERING_MODE_CENTER, "Center");
						stringMap.put(SCameraCharacteristics.METERING_MODE_MATRIX, "Matrix");
						stringMap.put(SCameraCharacteristics.METERING_MODE_SPOT, "Spot");
						stringMap.put(SCameraCharacteristics.METERING_MODE_MANUAL, "Manual");

						foreach (int mode in mCharacteristics.get(SCameraCharacteristics.METERING_AVAILABLE_MODES))
						{
							builder.Append(string.Format("\t\t{0}\n", stringMap.get(mode)));
						}
					}
					else
					{
						builder.Append("\t\tnot available\n");
					}
					builder.Append("\t]\n");

					// PAF.
					builder.Append("\tPhase AF: ");
					if (mCharacteristics.Keys.contains(SCameraCharacteristics.PHASE_AF_INFO_AVAILABLE))
					{
						builder.Append(mCharacteristics.get(SCameraCharacteristics.PHASE_AF_INFO_AVAILABLE)).Append("\n");
					}
					else
					{
						builder.Append("not available\n");
					}

					// Stabilization operation mode.
					builder.Append("\tStabilization modes: ");
					if (mCharacteristics.Keys.contains(SCameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION_OPERATION_MODE))
					{
						builder.Append(Arrays.ToString(mCharacteristics.get(SCameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION_OPERATION_MODE))).Append("\n");
					}
					else
					{
						builder.Append("not available\n");
					}
				}
			}

			builder.Append("</pre></body></html>");

			View dialogView = LayoutInflater.inflate(R.layout.information_dialog_single, null);
			((WebView)dialogView.findViewById(R.id.information)).loadDataWithBaseURL(null, builder.ToString(), "text/html", "utf-8", null);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("Information").setView(dialogView).setPositiveButton([email protected], new OnClickListenerAnonymousInnerClassHelper2(this, dialog));

			runOnUiThread(() =>
			{
				dialog.show();
			});
		}
Пример #19
0
        private void ScanUPC()
        {
            string oqty, rqty;

            if (Convert.ToInt32(txtScanUPC.Text.Length) > 1)
            {
                if (txtScanUPC.Text.Substring(Convert.ToInt32(txtScanUPC.Text.Length) - 1, 1) == "\n")
                {
                    if (txtScanUPC.Text != (""))
                    {
                        if (scan == true)
                        {
                            var scanItem = ((WMSApplication)Application).ItemRepository.GetRPoUPC(Intent.GetStringExtra("receiver_num"), Intent.GetStringExtra("division_id"), txtScanUPC.Text);
                            if (scanItem != null)
                            {
                                oqty = scanItem.oqty;
                                rqty = scanItem.rqty;

                                string stat = "0";
                                if (Convert.ToInt32(rqty) + 1 == Convert.ToInt32(oqty))
                                {
                                    stat = "1";
                                }
                                PoDetails.id           = scanItem.id;
                                PoDetails.receiver_num = scanItem.receiver_num;
                                PoDetails.division_id  = scanItem.division_id;
                                PoDetails.upc          = scanItem.upc;
                                PoDetails.description  = scanItem.description;
                                PoDetails.oqty         = oqty;
                                PoDetails.rqty         = Convert.ToString(Convert.ToInt32(rqty) + 1);
                                PoDetails.status       = stat;

                                ((WMSApplication)Application).ItemRepository.UpdateRPoListDetail(PoDetails);
                                refreshItems();
                            }
                            else
                            {
                                var builder = new AlertDialog.Builder(this);
                                builder.SetTitle("Debenhams");
                                builder.SetMessage("You scanned a UPC not in the P.O.\n\nUPC: " + txtScanUPC.Text + "\nDo you want to add UPC in P.O?");
                                builder.SetPositiveButton("Yes", AddInvalidUPC_Clicked);
                                builder.SetNegativeButton("No", delegate { builder.Dispose(); });
                                builder.Show();
                            }
                        }
                        else
                        {
                            txtslot.Text        = txtScanUPC.Text.Substring(0, Convert.ToInt32(txtScanUPC.Text.Length - 1));
                            PoList.id           = Convert.ToInt32(Intent.GetStringExtra("id"));
                            PoList.po_num       = Intent.GetStringExtra("po_num");
                            PoList.receiver_num = Intent.GetStringExtra("receiver_num");
                            PoList.division_id  = Intent.GetStringExtra("division_id");
                            PoList.division     = Intent.GetStringExtra("division");
                            PoList.slot_num     = txtslot.Text;
                            PoList.status       = "In Process";
                            ((WMSApplication)Application).ItemRepository.UpdateRPoListSlot(PoList);
                        }
                    }
                }
            }
        }
		public override bool onOptionsItemSelected(MenuItem item)
		{
			int id = item.ItemId;
			switch (id)
			{
				case R.id.action_new_thing:
					renderNewThingPopup();
					break;
				case R.id.change_floor:
					renderChangeCarpetPopup();
					break;
				case R.id.action_rotate:
					if (mSelectedThing != null)
					{
						int rotation = mSelectedThing.Rotation;

						if (rotation >= 270)
						{
							mSelectedThing.Rotation = 0;
						}
						else
						{
							mSelectedThing.Rotation = rotation + 90;
						}
						updateOfficeThing(mSelectedThing.Key, mSelectedThing);
					}
					break;
				case R.id.action_delete:
					deleteOfficeThing(mSelectedThing.Key, mSelectedThing);
					break;
				case R.id.action_edit:
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.widget.EditText entry = new android.widget.EditText(this);
					EditText entry = new EditText(this);

					builder.setMessage(getString([email protected]_desk_name_description)).setTitle(getString([email protected]_desk_name_title)).setView(entry);

					builder.setPositiveButton(getString([email protected]_desk_name_save), new OnClickListenerAnonymousInnerClassHelper(this, id, entry));
					builder.show();
					break;
			}
			return base.onOptionsItemSelected(item);
		}
Пример #21
0
        private void EditTask(int index, String titel, String omschrijving, String plaats, TimeSpan beginUur, TimeSpan eindUur)
        {
            int            item           = database.getId(index);
            LayoutInflater layoutInflater = LayoutInflater.From(this);
            View           promptView     = layoutInflater.Inflate(Resource.Layout.taakLayout, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.SetView(promptView);
            alertDialogBuilder.SetTitle("Wijzigen van de taak");

            EditText toonTitel        = (EditText)promptView.FindViewById(Resource.Id.edittextTitel);
            EditText toonOmschrijving = (EditText)promptView.FindViewById(Resource.Id.edittextOmschrijving);
            EditText toonPlaats       = (EditText)promptView.FindViewById(Resource.Id.edittextPlaats);

            TimePicker toonBegin = (TimePicker)promptView.FindViewById(Resource.Id.timePickerBegin);

            toonBegin.SetIs24HourView(Java.Lang.Boolean.True);
            TimePicker toonEinde = (TimePicker)promptView.FindViewById(Resource.Id.timePickerEind);

            toonEinde.SetIs24HourView(Java.Lang.Boolean.True);

            toonTitel.Text        = titel;
            toonOmschrijving.Text = omschrijving;
            toonPlaats.Text       = plaats;

            toonBegin.CurrentHour   = (Java.Lang.Integer)(beginUur.Hours);
            toonBegin.CurrentMinute = (Java.Lang.Integer)(beginUur.Minutes);

            toonEinde.CurrentHour   = (Java.Lang.Integer)(eindUur.Hours);
            toonEinde.CurrentMinute = (Java.Lang.Integer)(eindUur.Minutes);


            alertDialogBuilder.SetPositiveButton("Opslaan", (senderAlert, args) =>
            {
                toonBegin.ClearFocus();
                toonEinde.ClearFocus();
                TimeSpan beginuur = new TimeSpan(Convert.ToInt32(toonBegin.CurrentHour), Convert.ToInt32(toonBegin.CurrentMinute), 0);
                TimeSpan einduur  = new TimeSpan(Convert.ToInt32(toonEinde.CurrentHour), Convert.ToInt32(toonEinde.CurrentMinute), 0);
                database.ChangeToTable(item, datum, toonTitel.Text, toonPlaats.Text, toonOmschrijving.Text, beginuur, einduur);
                ListView taskList    = FindViewById <ListView>(Resource.Id.listView1);
                List <string> taken  = database.getFromTable(datum);
                ArrayAdapter adapter = new ArrayAdapter <String>(this, Resource.Layout.TextViewItem, taken);
                taskList.Adapter     = adapter;
            });

            alertDialogBuilder.SetNegativeButton("Annuleren", (senderAlert, args) =>
            {
            });

            AlertDialog alert = alertDialogBuilder.Create();

            alert.Show();
            toonTitel.TextChanged += (object sendere, Android.Text.TextChangedEventArgs tekst) =>
            {
                if (tekst.Text.ToString() == "")
                {
                    alert.GetButton((int)DialogButtonType.Positive).Enabled = false;
                }
                else
                {
                    alert.GetButton((int)DialogButtonType.Positive).Enabled = true;
                }
            };
        }
Пример #22
0
        private void ButtonTaskOnClick(object sender, System.EventArgs e)
        {
            LayoutInflater layoutInflater = LayoutInflater.From(this);
            View           promptView     = layoutInflater.Inflate(Resource.Layout.taakLayout, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.SetView(promptView);

            EditText titel        = (EditText)promptView.FindViewById(Resource.Id.edittextTitel);
            EditText omschrijving = (EditText)promptView.FindViewById(Resource.Id.edittextOmschrijving);
            EditText plaats       = (EditText)promptView.FindViewById(Resource.Id.edittextPlaats);

            TimePicker begin = (TimePicker)promptView.FindViewById(Resource.Id.timePickerBegin);

            begin.SetIs24HourView(Java.Lang.Boolean.True);
            TimePicker einde = (TimePicker)promptView.FindViewById(Resource.Id.timePickerEind);

            einde.SetIs24HourView(Java.Lang.Boolean.True);
            int      uurBegin = 0, minutenBegin = 0;
            int      uurEinde, minutenEinde = 0;
            TimeSpan beginuur, einduur;

            alertDialogBuilder.SetTitle("Taak toevoegen");
            alertDialogBuilder.SetPositiveButton("OK", (senderAlert, args) =>
            {
                begin.ClearFocus();
                einde.ClearFocus();
                uurBegin     = Convert.ToInt32(begin.CurrentHour);
                minutenBegin = Convert.ToInt32(begin.CurrentMinute);
                uurEinde     = Convert.ToInt32(einde.CurrentHour);
                minutenEinde = Convert.ToInt32(einde.CurrentMinute);
                beginuur     = new TimeSpan(uurBegin, minutenBegin, 0);
                einduur      = new TimeSpan(uurEinde, minutenEinde, 0);
                // calendar.addTaak(titel.Text, omschrijving.Text, plaats.Text, beginuur, einduur);
                database.addToTable(datum, titel.Text, plaats.Text, omschrijving.Text, beginuur, einduur);
                ListView taskList    = FindViewById <ListView>(Resource.Id.listView1);
                List <string> taken  = database.getFromTable(datum);
                ArrayAdapter adapter = new ArrayAdapter <String>(this, Resource.Layout.TextViewItem, taken);
                taskList.Adapter     = adapter;
            });
            alertDialogBuilder.SetNegativeButton("Annuleer", (senderAlert, args) =>
            {
            });
            AlertDialog alert = alertDialogBuilder.Create();


            alert.Show();



            alert.GetButton((int)DialogButtonType.Positive).Enabled = false;
            titel.TextChanged += (object sendere, Android.Text.TextChangedEventArgs tekst) =>
            {
                if (tekst.Text.ToString() == "")
                {
                    alert.GetButton((int)DialogButtonType.Positive).Enabled = false;
                }
                else
                {
                    alert.GetButton((int)DialogButtonType.Positive).Enabled = true;
                }
            };
        }
Пример #23
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Dialog to display
            LinearLayout dialogView = null;

            // Get the context for creating the dialog controls
            Android.Content.Context ctx = this.Activity.ApplicationContext;

            // Set a dialog title
            this.Dialog.SetTitle("Save Map to Portal");

            try
            {
                base.OnCreateView(inflater, container, savedInstanceState);

                // The container for the dialog is a vertical linear layout
                dialogView             = new LinearLayout(ctx);
                dialogView.Orientation = Orientation.Vertical;

                // Add a text box for entering a title for the new web map
                _mapTitleTextbox      = new EditText(ctx);
                _mapTitleTextbox.Hint = "Title";
                dialogView.AddView(_mapTitleTextbox);

                // Add a text box for entering a description
                _mapDescriptionTextbox      = new EditText(ctx);
                _mapDescriptionTextbox.Hint = "Description";
                dialogView.AddView(_mapDescriptionTextbox);

                // Add a text box for entering tags (populate with some values so the user doesn't have to fill this in)
                _tagsTextbox      = new EditText(ctx);
                _tagsTextbox.Text = "ArcGIS Runtime, Web Map";
                dialogView.AddView(_tagsTextbox);

                // Add a button to save the map
                Button saveMapButton = new Button(ctx);
                saveMapButton.Text   = "Save";
                saveMapButton.Click += SaveMapButtonClick;
                dialogView.AddView(saveMapButton);

                // If there's an existing portal item, configure the dialog for "update" (read-only entries)
                if (this._portalItem != null)
                {
                    _mapTitleTextbox.Text    = this._portalItem.Title;
                    _mapTitleTextbox.Enabled = false;

                    _mapDescriptionTextbox.Text    = this._portalItem.Description;
                    _mapDescriptionTextbox.Enabled = false;

                    _tagsTextbox.Text    = string.Join(",", this._portalItem.Tags);
                    _tagsTextbox.Enabled = false;

                    // Change some of the control text
                    this.Dialog.SetTitle("Save Changes to Map");
                    saveMapButton.Text = "Update";
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                var alertBuilder = new AlertDialog.Builder(this.Activity);
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }

            // Return the new view for display
            return(dialogView);
        }
        public void CallApi()
        {
            /*
             * progressbar.Visibility = ViewStates.Visible;
             * contentWebview.Visibility = ViewStates.Gone;
             */

            Task.Factory.StartNew(() =>
            {
                //Armando el objeto para consumir API movements
                //No borrar Declara o nó

                var header = new Models.Request.Aggregation.Header
                {
                    token = HomeActivity.GetInstance().access_token,
                };

                var documentFile1 = new Models.Request.Aggregation.Document
                {
                    bank_id = "0001",
                    financialProduct_type = "Credit Card",
                    data_file             = System.Text.Encoding.UTF8.GetBytes(oneFile.Text).ToString(),
                };

                var documentFile2 = new Models.Request.Aggregation.Document
                {
                    bank_id = "0001",
                    financialProduct_type = "Credit Card",
                    data_file             = System.Text.Encoding.UTF8.GetBytes(secondFile.Text).ToString(),
                };

                var documentsFileArray = new List <Models.Request.Aggregation.Document>();
                documentsFileArray.Add(documentFile1);
                documentsFileArray.Add(documentFile2);

                var datum = new Models.Request.Aggregation.Datum
                {
                    header   = header,
                    document = documentsFileArray
                };


                var requestModel = new Models.Request.Aggregation.RootObject
                {
                    data = new List <Models.Request.Aggregation.Datum>()
                };
                requestModel.data.Add(datum);



                var ResponseValiateStatement = ApiService.AggreationUploadFile(
                    Constants.Url.AggregationServicePrefix,
                    requestModel).Result;

                if (!ResponseValiateStatement.IsSuccess)
                {
                    RunOnUiThread(() =>
                    {
                        /*progressbar.Visibility = Android.Views.ViewStates.Gone;*/
                        Android.App.AlertDialog.Builder dialog1 = new AlertDialog.Builder(this);
                        AlertDialog alert1 = dialog1.Create();
                        alert1.SetTitle("Lo sentimos");
                        alert1.SetMessage("Hubo un error inesperado");
                        alert1.SetButton("Reintentar", (c, ev) =>
                                         { CallApi(); });
                        alert1.SetButton2("CANCEL", (c, ev) => {
                            var intent2 = new Intent(this, typeof(DataFileActivity));
                            StartActivity(intent2);
                            Finish();
                        });
                        alert1.Show();
                        return;
                    });
                }

                /*RunOnUiThread(() =>
                 * {
                 *      progressbar.Visibility = Android.Views.ViewStates.Gone;
                 * contentWebview.Visibility = Android.Views.ViewStates.Visible;
                 * });*/

                var ResponseAgregation = (Models.Responses.Aggregation.RootObject)ResponseValiateStatement.Result;
                if (ResponseAgregation.data[0].header.status == 200)
                {
                    RunOnUiThread(() =>
                    {
                        Android.App.AlertDialog.Builder dialogs = new AlertDialog.Builder(this);
                        AlertDialog alerts = dialogs.Create();
                        alerts.SetTitle("Operación exitosa");
                        alerts.SetMessage("Tus datos se han enviado exitosamente. En pocos minutos recibiras respuesta");
                        alerts.SetButton("Aceptar", (c, ev) =>
                        {
                            /*var intent2 = new Intent(this, typeof(DataFileActivity));
                             * StartActivity(intent2);*/
                            Finish();
                        });

                        alerts.Show();
                    });
                    return;
                }
                RunOnUiThread(() =>
                {
                    Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    AlertDialog alert = dialog.Create();
                    alert.SetTitle("Lo sentimos");
                    alert.SetMessage("Hubo un error inesperado");
                    alert.SetButton("Reintentar", (c, ev) =>
                                    { CallApi(); });
                    alert.SetButton2("CANCEL", (c, ev) => {
                        var intent2 = new Intent(this, typeof(DataFileActivity));
                        StartActivity(intent2);
                        Finish();
                    });
                    alert.Show();
                });
            });
        }
Пример #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            //Vraag om bericht te sturen na het terugkomen van een telefoon
            if (Globals.CALLED == true)
            {
                AlertDialog.Builder sendMessage = new AlertDialog.Builder(this);
                sendMessage.SetTitle("gegevens verzenden?");
                sendMessage.SetMessage("Wil je je naam en Chirogroep per sms versturen?.");
                sendMessage.SetPositiveButton("Ja", delegate {
                    sendSms();
                });
                sendMessage.SetNegativeButton("Neen", delegate {});
                sendMessage.Show();
            }


            TabHost.TabSpec spec;                 // Resusable TabSpec for each tab
            Intent          intent;               // Reusable Intent for each tab

            // Create an Intent to launch an Activity for the tab (to be reused)
            intent = new Intent(this, typeof(Activity1));
            intent.AddFlags(ActivityFlags.NewTask);

            // Initialize a TabSpec for each tab and add it to the TabHost
            spec = TabHost.NewTabSpec("Op Bivak");
            spec.SetIndicator("", Resources.GetDrawable(Resource.Drawable.tab_main));
            //spec.SetIndicator ("Main", null);
            spec.SetContent(intent);
            TabHost.AddTab(spec);

            // Do the same for the other tabs
            intent = new Intent(this, typeof(EmergencyActivity));
            intent.AddFlags(ActivityFlags.NewTask);

            spec = TabHost.NewTabSpec("Emergency");
            spec.SetIndicator("", Resources.GetDrawable(Resource.Drawable.tab_sos_red));
            //spec.SetIndicator ("Settings", null);
            spec.SetContent(intent);
            TabHost.AddTab(spec);

            intent = new Intent(this, typeof(FaqActivity));
            intent.AddFlags(ActivityFlags.NewTask);

            spec = TabHost.NewTabSpec("FAQ");
            spec.SetIndicator("", Resources.GetDrawable(Resource.Drawable.tab_faq));
            //spec.SetIndicator ("Settings", null);
            spec.SetContent(intent);
            TabHost.AddTab(spec);

            intent = new Intent(this, typeof(SettingsActivity));
            intent.AddFlags(ActivityFlags.NewTask);
            spec = TabHost.NewTabSpec("Settings");
            spec.SetIndicator("", Resources.GetDrawable(Resource.Drawable.tab_settings));
            //spec.SetIndicator ("Settings", null);
            spec.SetContent(intent);
            TabHost.AddTab(spec);



            TabHost.CurrentTab = 0;
        }
Пример #26
0
        protected override void OnResume()
        {
            base.OnResume();
            _design.ReapplyTheme();

            CheckIfUnloaded();

            InitFingerprintUnlock();

            bool showKeyboard = true;

            EditText pwd = (EditText)FindViewById(Resource.Id.QuickUnlock_password);

            pwd.PostDelayed(() =>
            {
                InputMethodManager keyboard = (InputMethodManager)GetSystemService(Context.InputMethodService);
                if (showKeyboard)
                {
                    keyboard.ShowSoftInput(pwd, 0);
                }
                else
                {
                    keyboard.HideSoftInputFromWindow(pwd.WindowToken, HideSoftInputFlags.ImplicitOnly);
                }
            }, 50);


            var btn = FindViewById <ImageButton>(Resource.Id.fingerprintbtn);

            btn.Click += (sender, args) =>
            {
                if ((_biometryIdentifier != null) && ((_biometryIdentifier.HasUserInterface) || string.IsNullOrEmpty((string)btn.Tag)))
                {
                    _biometryIdentifier.StartListening(this);
                }
                else
                {
                    AlertDialog.Builder b = new AlertDialog.Builder(this);
                    b.SetTitle(Resource.String.fingerprint_prefs);
                    b.SetMessage(btn.Tag.ToString());
                    b.SetPositiveButton(Android.Resource.String.Ok, (o, eventArgs) => ((Dialog)o).Dismiss());
                    if (_biometryIdentifier != null)
                    {
                        b.SetNegativeButton(Resource.String.disable_sensor, (senderAlert, alertArgs) =>
                        {
                            btn.SetImageResource(Resource.Drawable.ic_fingerprint_error);
                            _biometryIdentifier?.StopListening();
                            _biometryIdentifier = null;
                        });
                    }
                    else
                    {
                        b.SetNegativeButton(Resource.String.enable_sensor, (senderAlert, alertArgs) =>
                        {
                            InitFingerprintUnlock();
                        });
                    }
                    b.Show();
                }
            };
        }
Пример #27
0
        private void AddCharacterList(LayoutInflater inflater, ViewGroup container, View v, int id, bool monsters)
        {
            LinearLayout cl = (LinearLayout)inflater.Inflate(Resource.Layout.CharacterList, container, false);

            cl.LayoutParameters = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent, 1f);

            ListView lv = cl.FindViewById <ListView>(Resource.Id.characterList);

            lv.Adapter       = (new CharacterListAdapter(_CombatState, monsters));
            lv.ItemSelected += (sender, e) => {
                Character c = ((BaseAdapter <Character>)lv.Adapter)[e.Position];
                ShowCharacter(v, c);
            };
            lv.ItemClick += (sender, e) => {
                Character c = ((BaseAdapter <Character>)lv.Adapter)[e.Position];
                ShowCharacter(v, c);
            };
            if (!monsters)
            {
                _PlayerList = lv;
            }
            else
            {
                _MonsterList = lv;
            }

            lv.SetOnDragListener(new ListOnDragListener(monsters, v));

            cl.FindViewById <ImageButton>(Resource.Id.blankButton).Click +=
                (object sender, EventArgs e) =>
            {
                _CombatState.AddBlank(monsters);
            };


            cl.FindViewById <ImageButton>(Resource.Id.monsterButton).Click +=
                (object sender, EventArgs e) =>
            {
                MonsterPickerDialog dl = new MonsterPickerDialog(v.Context, monsters, _CombatState);
                dl.Show();
            };

            cl.FindViewById <ImageButton>(Resource.Id.loadButton).Click +=
                (object sender, EventArgs e) =>
            {
                FileDialog fd = new FileDialog(cl.Context, _Extensions, true);
                fd.Show();

                fd.DialogComplete += (object s, FileDialog.FileDialogEventArgs ea) =>
                {
                    string name     = ea.Filename;
                    string fullname = Path.Combine(fd.Folder, name);

                    FileInfo file = new FileInfo(fullname);

                    if (String.Compare(".por", file.Extension, true) == 0 || String.Compare(".rpgrp", file.Extension, true) == 0)
                    {
                        List <Monster> importmonsters = Monster.FromFile(fullname);

                        if (importmonsters != null)
                        {
                            foreach (Monster m in importmonsters)
                            {
                                Character ch = new Character(m, false);
                                ch.IsMonster = monsters;
                                _CombatState.AddCharacter(ch);
                            }
                        }
                    }
                    else
                    {
                        List <Character> l = XmlListLoader <Character> .Load(fullname);

                        foreach (var c in l)
                        {
                            c.IsMonster = monsters;
                            _CombatState.AddCharacter(c);
                        }
                    }
                };
            };

            cl.FindViewById <ImageButton>(Resource.Id.saveButton).Click +=
                (object sender, EventArgs e) =>
            {
                FileDialog fd = new FileDialog(v.Context, _Extensions, false);
                fd.DialogComplete += (object s, FileDialog.FileDialogEventArgs ea) =>
                {
                    string name = ea.Filename;
                    if (!name.EndsWith(".cmpt", StringComparison.CurrentCultureIgnoreCase))
                    {
                        name = name + ".cmpt";
                    }
                    string fullname = Path.Combine(fd.Folder, name);

                    XmlListLoader <Character> .Save(new List <Character>(_CombatState.Characters.Where((a) => a.IsMonster == monsters)), fullname);
                };
                fd.Show();
            };

            cl.FindViewById <Button>(Resource.Id.clearButton).Click +=
                (object sender, EventArgs e) =>
            {
                AlertDialog.Builder bui = new AlertDialog.Builder(v.Context);
                bui.SetMessage("Clear " + (monsters?"Monsters":"Players") + " List?");
                bui.SetPositiveButton("OK", (a, x) => {
                    List <Character> removeList = new List <Character>(from c in _CombatState.Characters where c.IsMonster == monsters select c);
                    foreach (Character c in removeList)
                    {
                        _CombatState.RemoveCharacter(c);
                    }
                });
                bui.SetNegativeButton("Cancel", (a, x) => {});
                bui.Show();
            };

            if (monsters)
            {
                _XPText = cl.FindViewById <TextView>(Resource.Id.xpText);
                ReloadXPText();
            }



            v.FindViewById <LinearLayout>(id).AddView(cl);
        }
        private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea)
        {
            // Set up UI for download.
            _downloadDeleteProgressDialog.Progress = 0;
            _downloadDeleteProgressDialog.SetMessage("Downloading map area...");
            _downloadDeleteProgressDialog.SetTitle("Downloading");
            _downloadDeleteProgressDialog.Show();

            // Get the path for the downloaded map area.
            var path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title);

            // If the map area is already downloaded, open it and don't download it again.
            if (Directory.Exists(path))
            {
                var localMapArea = await MobileMapPackage.OpenAsync(path);

                try
                {
                    // Load the map area.
                    _myMapView.Map = localMapArea.Maps.First();

                    // Update the UI.
                    _downloadDeleteProgressDialog.Dismiss();

                    // Return without downloading the item again.
                    return;
                }
                catch (Exception)
                {
                    // Do nothing, continue as if the map wasn't downloaded.
                }
            }

            // Create the job that is used to download the map area.
            DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(mapArea, path);

            // Subscribe to progress change events to support showing a progress bar.
            job.ProgressChanged += OnJobProgressChanged;

            try
            {
                // Download the map area.
                DownloadPreplannedOfflineMapResult results = await job.GetResultAsync();

                // Handle possible errors and show them to the user.
                if (results.HasErrors)
                {
                    var errorBuilder = new StringBuilder();

                    // Add layer errors to the message.
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine($"{layerError.Key.Name} {layerError.Value.Message}");
                    }

                    // Add table errors to the message.
                    foreach (KeyValuePair <FeatureTable, Exception> tableError in results.TableErrors)
                    {
                        errorBuilder.AppendLine($"{tableError.Key.TableName} {tableError.Value.Message}");
                    }

                    // Show the error message.
                    var builder = new AlertDialog.Builder(this);
                    builder.SetMessage(errorBuilder.ToString()).SetTitle("Warning!").Show();
                }

                // Show the Map in the MapView.
                _myMapView.Map = results.OfflineMap;
            }
            catch (Exception ex)
            {
                // Report exception.
                var builder = new AlertDialog.Builder(this);
                builder.SetMessage(ex.Message).SetTitle("Downloading map area failed.").Show();
            }
            finally
            {
                // Clear the loading UI.
                _downloadDeleteProgressDialog.Dismiss();
            }
        }
 void Upload(bool ShowMessage = true)
 {
     if (!ActivateButton.Checked)
     {
         Toast.MakeText(this, "Das Messen wurde deaktiviert", ToastLength.Long).Show();
         Functions.SaveError(new Exception("User disabled capturing data"), "Upload_Data");
         return;
     }
     RunOnNewThread(delegate {
         #region Request
         try
         {
             var req         = WebRequest.Create("https://umwelt.wasweisich.com/apply/");
             req.Credentials = new NetworkCredential("jonjon0815", "Toaster1144");
             req.Method      = "POST";
             req.ContentType = "application/x-www-form-urlencoded";
             string a        = "0", b = "0";
             if (MyLocation != null)
             {
                 a = MyLocation.Latitude.ToString().Replace(',', '.');
                 b = MyLocation.Longitude.ToString().Replace(',', '.');
             }
             else
             {
                 RunOnUiThread(delegate {
                     if (ShowMessage)
                     {
                         //Toast.MakeText(this, "Keine Position verfügbar!", ToastLength.Long).Show();
                         var dialog = new AlertDialog.Builder(this);
                         dialog.SetTitle("Keine Position verfügbar!");
                         dialog.SetMessage("Ohne GPS können Sie keine Daten hochladen." + System.Environment.NewLine + "Bitte warten Sie, bis Ihr Standort verfügbar ist.");
                         dialog.SetPositiveButton("OK", delegate { });
                         dialog.SetIcon(Resources.GetDrawable(Resource.Drawable.Warning));
                         dialog.Show();
                     }
                     else
                     {
                         Toast.MakeText(this, "Keine Position", ToastLength.Short).Show();
                     }
                 });
                 Functions.SaveError(new Exception("No Position while Upload"), "Upload_Data");
                 return;
             }
             var Kommentar = "";
             if (MyTrafficType == TrafficType.Auto)
             {
                 Kommentar += "[In Auto ect gemessen]";
             }
             var data          = System.Text.Encoding.UTF8.GetBytes("Latitude=" + a + "&Longitude=" + b + "&DB=" + _db.ToString() + "&Kommentar=" + Kommentar);
             req.ContentLength = data.Length;
             var stream        = req.GetRequestStream();
             stream.Write(data, 0, data.Length);
             stream.Flush();
             stream.Close();
             stream.Dispose();
             var res    = req.GetResponse();
             var str2   = res.GetResponseStream();
             var respst = new StreamReader(str2).ReadToEnd();
             RunOnUiThread(delegate { Toast.MakeText(this, respst, ToastLength.Short).Show(); });
             str2.Close();
             str2.Dispose();
             res.Dispose();
             req.Abort();
         }
         catch (Exception ex) {
             RunOnUiThread(delegate {
                 Toast.MakeText(this, "Fehler beim Hochladen!", ToastLength.Short).Show();
             });
             Functions.SaveError(ex, "Upload_Data");
         }
         #endregion
     });
 }
        private async void Initialize()
        {
            try
            {
                // Show a loading indicator.
                ProgressDialog progressIndicator = new ProgressDialog(this);
                progressIndicator.SetTitle("Loading");
                progressIndicator.SetMessage("Loading the available map areas.");
                progressIndicator.SetCancelable(false);
                progressIndicator.Show();

                // Get the offline data folder.
                _offlineDataFolder = Path.Combine(GetDataFolder(),
                                                  "SampleData", "DownloadPreplannedMapAreas");

                // If the temporary data folder doesn't exist, create it.
                if (!Directory.Exists(_offlineDataFolder))
                {
                    Directory.CreateDirectory(_offlineDataFolder);
                }

                // Create a portal that contains the portal item.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Create a webmap based on the id.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, PortalItemId);

                // Create the offline task and load it.
                _offlineMapTask = await OfflineMapTask.CreateAsync(webmapItem);

                // Query related preplanned areas.
                _preplannedMapAreas = await _offlineMapTask.GetPreplannedMapAreasAsync();

                // Load each preplanned map area.
                foreach (var area in _preplannedMapAreas)
                {
                    await area.LoadAsync();
                }

                // Show a popup menu of available areas when the download button is clicked.
                _downloadButton.Click += (s, e) =>
                {
                    // Create a menu to show the available map areas.
                    PopupMenu areaMenu = new PopupMenu(this, _downloadButton);
                    areaMenu.MenuItemClick += (sndr, evt) =>
                    {
                        // Get the name of the selected area.
                        string selectedArea = evt.Item.TitleCondensedFormatted.ToString();

                        // Download and show the map.
                        OnDownloadMapAreaClicked(selectedArea);
                    };

                    // Create the menu options.
                    foreach (PreplannedMapArea area in _preplannedMapAreas)
                    {
                        areaMenu.Menu.Add(area.PortalItem.Title.ToString());
                    }

                    // Show the menu in the view.
                    areaMenu.Show();
                };

                // Remove loading indicators from the UI.
                progressIndicator.Dismiss();
            }
            catch (Exception ex)
            {
                // Something unexpected happened, show error message.
                var builder = new AlertDialog.Builder(this);
                builder.SetMessage(ex.Message).SetTitle("An error occurred").Show();
            }
        }
Пример #31
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            string      selected_menu;
            ImageButton popupmenu = FindViewById <ImageButton>(Resource.Id.popupButton);

            popupmenu.Click += (s, arg) =>
            {
                PopupMenu menu = new PopupMenu(this, popupmenu);
                menu.Inflate(Resource.Menu.popupmenu);
                menu.MenuItemClick += (si, arg1) =>
                {
                    selected_menu = arg1.Item.TitleFormatted.ToString();
                    if (selected_menu == "Show completed consignments")
                    {
                        this.ConsignmentDetailViewModel.Show_complete_consignment();
                    }
                    else if (selected_menu == "Logout")
                    {
                        AlertDialog.Builder alert = new AlertDialog.Builder(this);
                        alert.SetTitle("Logout");
                        alert.SetMessage("Are you sure?");
                        alert.SetPositiveButton("Yes", async(senderAlert, args) =>
                        {
                            await GetLogoutInfo();
                            if (result == 1)
                            {
                                LocalStorage.SaveSet("login_session_id", null);
                                Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                            }
                            else
                            {
                                var linearLayout           = FindViewById <LinearLayout>(Resource.Id.consignmentdetailview);
                                Snackbar snackbar          = Snackbar.Make(linearLayout, "Log out error!", Snackbar.LengthLong);
                                Android.Views.View objView = snackbar.View;
                                TextView txtAction         = objView.FindViewById <TextView>(Resource.Id.snackbar_action);
                                txtAction.SetTextSize(Android.Util.ComplexUnitType.Dip, 18);
                                txtAction.SetTextColor(Android.Graphics.Color.White);
                                objView.SetBackgroundColor(Color.Red);
                                //set message text color
                                TextView txtMessage = objView.FindViewById <TextView>(Resource.Id.snackbar_text);
                                txtMessage.SetTextColor(Android.Graphics.Color.White);
                                txtMessage.SetTextSize(Android.Util.ComplexUnitType.Dip, 18);
                                snackbar.Show();
                                Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                            }
                        });
                        alert.SetNegativeButton("No", (senderAlert, args) =>
                        {
                        });
                        RunOnUiThread(() =>
                        {
                            alert.Show();
                        });
                    }
                    else if (selected_menu == "Use bluetooth scanner")
                    {
                        this.ConsignmentDetailViewModel.Use_bluetooth_scanner();
                    }
                    else if (selected_menu == "Use camera scanner")
                    {
                        this.ConsignmentDetailViewModel.Use_camera_scanner();
                    }
                    else if (selected_menu == "Enter SOTI Id")
                    {
                        this.ConsignmentDetailViewModel.Enter_SOTI_Id();
                    }
                    else
                    {
                        this.ConsignmentDetailViewModel.About();
                    }
                };
                menu.Show();
            };

            // Get the count value passed to us from SessionInfoView:
            //var x = Intent.Extras.GetStringArray("consignment");
            //string[] receiveconsignment = Intent.Extras.GetStringArray("newconsignment");

            ConsignmentDetailViewModel.ConsignmentinfoText    = "Consignment Info";
            ConsignmentDetailViewModel.SpecialInstructionText = "Length   3m";
            ConsignmentDetailViewModel.DriverAlertText        = "Driver Alert";
            ConsignmentDetailViewModel.AlertDetailsText       = "5 THE COURTYARD, FURLONG ROAD, BOURNE END, BUCKINGHAMSHIRE";

            var bindingSet = this.CreateBindingSet <ConsignmentDetailView, ConsignmentDetailViewModel>();

            bindingSet.Bind().For(c => c.Logout_error).To(vm => vm.Logout_error);
            bindingSet.Apply();
        }
Пример #32
0
        public void BTSalvar_Click(object sender, EventArgs e)
        {
            InstalacaoService avalService = new InstalacaoService();

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            AlertDialog         alerta  = builder.Create();

            if (idEstudo_ > 0)
            {
                if ((etComprimento.Text != "") && (etComprimento.Text != "") && (idPlantioSelect != "0"))
                {
                    var date = "";
                    if (textDate.Text == "")
                    {
                        date = DateTime.Now.ToString();
                    }
                    else
                    {
                        date = textDate.Text;
                    }


                    var aval = new Instalacao
                    {
                        idEstudo  = idEstudo_,
                        idPlantio = int.Parse(idPlantioSelect),
                        Tamanho_Parcela_Comprimento = decimal.Parse(etComprimento.Text.Replace(".", ",")),
                        Tamanho_Parcela_Largura     = decimal.Parse(etLargura.Text.Replace(".", ",")),
                        Coordenadas1    = etCoordenadas1.Text,
                        Coordenadas2    = etCoordenadas2.Text,
                        Altitude        = etAltitude.Text,
                        Data_Instalacao = Convert.ToDateTime(date),
                        idUsuario       = int.Parse(Settings.GeneralSettings),
                        Observacoes     = etObservacoes.Text
                    };

                    try
                    {
                        if (avalService.SalvarInstalacao(aval) == true)
                        {
                            alerta.SetTitle("Sucesso!");
                            alerta.SetIcon(Android.Resource.Drawable.IcInputAdd);
                            alerta.SetMessage("Instalação Salva com Sucesso!");
                            alerta.SetButton("OK", (s, ev) =>
                            {
                                alerta.Dismiss();
                            });
                            alerta.Show();
                            LimpaCampos();
                        }
                        else
                        {
                            alerta.SetTitle("ERRO!");
                            alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                            alerta.SetMessage("Erro ao salvar a Avaliação!");
                            alerta.SetButton("OK", (s, ev) =>
                            {
                                alerta.Dismiss();
                            });
                            alerta.Show();
                        }
                    }

                    catch

                    {
                        alerta.SetTitle("ERRO!");
                        alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                        alerta.SetMessage("Erro ao salvar a Avaliação!");
                        alerta.SetButton("OK", (s, ev) =>
                        {
                            alerta.Dismiss();
                        });
                        alerta.Show();
                    }
                }
                else
                {
                    alerta.SetMessage("Favor preencher todos os campos obrigatórios");
                    alerta.SetTitle("ERRO!");
                    alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                    alerta.SetMessage("Favor preencher os campos obrigatórios!");
                    alerta.SetButton("OK", (s, ev) =>
                    {
                        alerta.Dismiss();
                    });
                    alerta.Show();
                }
            }

            else
            {
                alerta.SetMessage("Favor informar um estudo válido ");
                alerta.SetTitle("ERRO!");
                alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                alerta.SetMessage("Favor informar um estudo válido!");
                alerta.SetButton("OK", (s, ev) =>
                {
                    alerta.Dismiss();
                });
                alerta.Show();
            }
        }
Пример #33
0
        private static AlertDialogInfo CreateDialog(
            string content,
            string title,
            string okText     = null,
            string cancelText = null,
            Action <bool> afterHideCallbackWithResponse = null)
        {
            var tcs = new TaskCompletionSource <bool>();

            var builder = new AlertDialog.Builder(ActivityBase.CurrentActivity);

            builder.SetMessage(content);
            builder.SetTitle(title);

            AlertDialog dialog = null;

            builder.SetPositiveButton(
                okText ?? "OK",
                (d, index) =>
            {
                tcs.TrySetResult(true);

                // ReSharper disable AccessToModifiedClosure
                if (dialog != null)
                {
                    dialog.Dismiss();
                    dialog.Dispose();
                }

                afterHideCallbackWithResponse?.Invoke(true);
                // ReSharper restore AccessToModifiedClosure
            });

            if (cancelText != null)
            {
                builder.SetNegativeButton(
                    cancelText,
                    (d, index) =>
                {
                    tcs.TrySetResult(false);

                    // ReSharper disable AccessToModifiedClosure
                    if (dialog != null)
                    {
                        dialog.Dismiss();
                        dialog.Dispose();
                    }

                    afterHideCallbackWithResponse?.Invoke(false);
                    // ReSharper restore AccessToModifiedClosure
                });
            }

            builder.SetOnDismissListener(
                new OnDismissListener(
                    () =>
            {
                tcs.TrySetResult(false);

                afterHideCallbackWithResponse?.Invoke(false);
            }));

            dialog = builder.Create();

            return(new AlertDialogInfo
            {
                Dialog = dialog,
                Tcs = tcs
            });
        }
 /// <summary>
 /// Method abstracts the platform-specific message box functionality to maximize re-use of common code
 /// </summary>
 /// <param name="message">Text of the message to show.</param>
 private void ShowStatusMessage(string message)
 {
     // Display the message to the user
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     builder.SetMessage(message).SetTitle("Alert").Show();
 }
        void SetupViewBindings()
        {
            btnBack.Click += (sender, args) => Finish();

            ShowHelpIfNecessary(TutorialHelper.TagEvents);

            lblTitle.Typeface = CustomTypefaces.RobotoBold;

            var layoutManager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);

            rvDates.SetLayoutManager(layoutManager);

            var times = new List <DateTime>();

            currentTime = DateTime.Now.Date;

            //   cureentTime = DateTime.Now.Date;

            //   currentTime = DateTime.Now.Date.ToUniversalTime();
            var startTime = DateTime.Now.Date.ToUniversalTime().AddDays(-2);

            for (int i = 0; i < 5; i++)
            {
                times.Add(startTime.AddDays(i));
            }

            rvDates.SetAdapter(new CustomRecyclerViewAdapter <DateTime>(times, BindViewHolder, CreateViewHolder, (time, i) => 0));

            adapter = new CustomListAdapter <EventProfile>(new List <EventProfile>(), GetView);
            adapter.NoContentText = "No Events";
            lvEvents.Adapter      = adapter;
            lvEvents.ItemClick   += (sender, e2) =>
            {
                var e = adapter[e2.Position];
                if (Post.Events.Contains((e.Id)))
                {
                    Post.Events.Remove(e.Id);
                }
                else
                {
                    Post.Events.Add(e.Id);
                }

                adapter.NotifyDataSetChanged();
            };
            GetData();

            btnPost.Click += (sender, e) =>
            {
                if (Post.Videos.Any(m => string.IsNullOrEmpty(m.Id)))
                {
                    new AlertDialog.Builder(this)
                    .SetTitle("Video Upload")
                    .SetMessage("You video will be uploaded in the background and the post will be made visible once the upload is complete")
                    .SetPositiveButton("Ok", (o, args) => SavePost())
                    .Show();
                }
                else
                {
                    SavePost();
                }
            };

            if (!string.IsNullOrEmpty(Post.Id))
            {
                btnShare.Visibility = ViewStates.Gone;
            }

            btnShare.Click += (sender, e) =>
            {
                var builder = new AlertDialog.Builder(this);
                builder.SetTitle("Share On");
                ApplicationInfo info = null;
                try
                {
                    info = PackageManager.GetApplicationInfo("com.facebook.katana", 0);
                }
                catch (PackageManager.NameNotFoundException ex)
                {
                }

                if ((Post.Images.Any() || Post.Links.Any() || Post.Videos.Any()) && info != null)
                {
                    builder.SetPositiveButton("Facebook", (s2, e2) =>
                    {
                        Sharer.ShareFacebook(Post);
                        Post.IsShared = true;
                    });
                }

                builder.SetNeutralButton("Other", (s2, e2) =>
                {
                    Sharer.ShareOther(Post);
                    Post.IsShared = true;
                });
                builder.SetNegativeButton("Cancel", (s2, e2) => {});
                builder.Show();
            };
        }
Пример #36
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            RequestWindowFeature(WindowFeatures.NoTitle);

            base.OnCreate(savedInstanceState);
            //SetContentView(Resource.Layout.FirstRun);
            SetContentView(Resource.Layout.ConnectionChecklist);

            //BranchAndroid.Init(this, Resources.GetString(Resource.String.BRANCHKEY), this);

            IsPlayServicesAvailable();

            var allprefs = GetSharedPreferences(WhiteLabelConfig.BUILD_VARIANT.ToLower(), FileCreationMode.Private);


            if (WhiteLabelConfig.LOCAL_SERVER)
            {
                Uri connectionuri = new Uri($"{WhiteLabelConfig.SERVER}:{WhiteLabelConfig.PORT}");
                Bootlegger.BootleggerClient.StartWithLocal(connectionuri);
            }

            var firstrun = true;

            var prefs = allprefs.GetBoolean("firstrun", false);

            firstrun = prefs;

            //detect wanting to go straight to uploads
            if (Intent.Extras != null && Intent.Extras.ContainsKey("upload"))
            {
                (Application as BootleggerApp).ReturnState = new BootleggerApp.ApplicationReturnState()
                {
                    ReturnsTo = BootleggerApp.ReturnType.OPEN_UPLOAD, Payload = Intent.Extras.GetString("eventid")
                };
                firstrun = true;
            }

            if (Intent.Extras != null && Intent.Extras.ContainsKey("advert"))
            {
                (Application as BootleggerApp).ADVERT = Intent.Extras.GetString("advert");
                firstrun = true;
            }
            else
            {
                (Application as BootleggerApp).ADVERT = "";
            }

            //detect login intent:
            //Console.WriteLine(Intent.Data?.Scheme);
            //Console.WriteLine(Intent.Data?.Host);

            if (Intent.Data != null && Intent.Data.Scheme == WhiteLabelConfig.DATASCHEME && Intent.Data.Host != "open")
            {
                var url = Intent.Data;

                if (!url.QueryParameterNames.Contains("eventid"))
                {
                    var session = url.Query;
                    session = session.TrimEnd('=');

                    //(Application as BootleggerApp).loginsession = HttpUtility.UrlEncode(session);

                    (Application as BootleggerApp).ReturnState.Session = HttpUtility.UrlEncode(session);
                    var returnstate = (Application as BootleggerApp).ReturnState;
                    //(Application as BootleggerApp).ReturnState = new BootleggerApp.ApplicationReturnState() { ReturnsTo = BootleggerApp.ReturnType.SIGN_IN_ONLY, Session = HttpUtility.UrlEncode(session) };

                    firstrun = true;
                }
                else
                {
                    //if its a create new shoot connect:
                    var eventid = url.GetQueryParameter("eventid");
                    (Application as BootleggerApp).ReturnState = new BootleggerApp.ApplicationReturnState()
                    {
                        ReturnsTo = BootleggerApp.ReturnType.OPEN_SHOOT, Payload = eventid
                    };
                }
            }

            //edit invite:
            if (Intent.Data != null && Intent.Data.Host == WhiteLabelConfig.SERVERHOST && Intent.Data.PathSegments.Contains("watch"))
            {
                var editid = Intent.Data.PathSegments.Last();
                (Application as BootleggerApp).ReturnState = new BootleggerApp.ApplicationReturnState()
                {
                    ReturnsTo = BootleggerApp.ReturnType.OPEN_EDIT, Payload = editid
                };
            }

            string state = Android.OS.Environment.ExternalStorageState;

            if (state != Android.OS.Environment.MediaMounted)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetMessage(Resource.String.nostorageavail);
                builder.SetNeutralButton(Android.Resource.String.Ok, new EventHandler <DialogClickEventArgs>((o, q) =>
                {
                    Finish();
                }));
                builder.SetCancelable(false);
                builder.Show();
            }
            else
            {
                (Application as BootleggerApp).Start();
                Bootlegger.BootleggerClient.OnSessionLost += Comms_OnSessionLost;

                //check for firstrun:
                if (!firstrun && Bootlegger.BootleggerClient.CurrentUser == null && WhiteLabelConfig.ONBOARDING)
                {
                    FindViewById(Resource.Id.theroot).Visibility   = ViewStates.Visible;
                    FindViewById <Button>(Resource.Id.skip).Click += SplashActivity_Click;
                    FindViewById <Button>(Resource.Id.ok).Click   += OkActivity_Click;
                    FindViewById <Button>(Resource.Id.next).Click += NextActivity_Click;
                    var       mAdapter = new WizardPagerAdapter();
                    ViewPager mPager   = FindViewById <ViewPager>(Resource.Id.pager);
                    mPager.OffscreenPageLimit = 4;
                    //mPager.SetOnPageChangeListener(this);

                    mPager.Adapter       = mAdapter;
                    mPager.PageSelected += MPager_PageSelected;
                }
                else
                {
                    //StartActivity(typeof(Login));
                }
            }
        }
Пример #37
0
        public static void ShowChangeLog(Context ctx, Action onDismiss)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeHoloLightDialog));
            builder.SetTitle(ctx.GetString(Resource.String.ChangeLog_title));
            List <string> changeLog = new List <string> {
                BuildChangelogString(ctx, Resource.Array.ChangeLog_1_08c, "1.08c"),
                BuildChangelogString(ctx, Resource.Array.ChangeLog_1_08b, "1.08b"),
                BuildChangelogString(ctx, Resource.Array.ChangeLog_1_08, "1.08"),
                ctx.GetString(Resource.String.ChangeLog_1_07b),
                ctx.GetString(Resource.String.ChangeLog_1_07),
                ctx.GetString(Resource.String.ChangeLog_1_06),
                ctx.GetString(Resource.String.ChangeLog_1_05),
                ctx.GetString(Resource.String.ChangeLog_1_04b),
                ctx.GetString(Resource.String.ChangeLog_1_04),
                ctx.GetString(Resource.String.ChangeLog_1_03),
                ctx.GetString(Resource.String.ChangeLog_1_02),
#if !NoNet
                ctx.GetString(Resource.String.ChangeLog_1_01g),
                ctx.GetString(Resource.String.ChangeLog_1_01d),
#endif
                ctx.GetString(Resource.String.ChangeLog_1_01),
                ctx.GetString(Resource.String.ChangeLog_1_0_0e),
                ctx.GetString(Resource.String.ChangeLog_1_0_0),
                ctx.GetString(Resource.String.ChangeLog_0_9_9c),
                ctx.GetString(Resource.String.ChangeLog_0_9_9),
                ctx.GetString(Resource.String.ChangeLog_0_9_8c),
                ctx.GetString(Resource.String.ChangeLog_0_9_8b),
                ctx.GetString(Resource.String.ChangeLog_0_9_8),
#if !NoNet
                //0.9.7b fixes were already included in 0.9.7 offline
                ctx.GetString(Resource.String.ChangeLog_0_9_7b),
#endif
                ctx.GetString(Resource.String.ChangeLog_0_9_7),
                ctx.GetString(Resource.String.ChangeLog_0_9_6),
                ctx.GetString(Resource.String.ChangeLog_0_9_5),
                ctx.GetString(Resource.String.ChangeLog_0_9_4),
                ctx.GetString(Resource.String.ChangeLog_0_9_3_r5),
                ctx.GetString(Resource.String.ChangeLog_0_9_3),
                ctx.GetString(Resource.String.ChangeLog_0_9_2),
                ctx.GetString(Resource.String.ChangeLog_0_9_1),
                ctx.GetString(Resource.String.ChangeLog_0_9),
                ctx.GetString(Resource.String.ChangeLog_0_8_6),
                ctx.GetString(Resource.String.ChangeLog_0_8_5),
                ctx.GetString(Resource.String.ChangeLog_0_8_4),
                ctx.GetString(Resource.String.ChangeLog_0_8_3),
                ctx.GetString(Resource.String.ChangeLog_0_8_2),
                ctx.GetString(Resource.String.ChangeLog_0_8_1),
                ctx.GetString(Resource.String.ChangeLog_0_8),
                ctx.GetString(Resource.String.ChangeLog_0_7),
                ctx.GetString(Resource.String.ChangeLog)
            };

            String version;

            try {
                PackageInfo packageInfo = ctx.PackageManager.GetPackageInfo(ctx.PackageName, 0);
                version = packageInfo.VersionName;
            } catch (PackageManager.NameNotFoundException) {
                version = "";
            }

            string warning = "";

            if (version.Contains("pre"))
            {
                warning = ctx.GetString(Resource.String.PreviewWarning);
            }

            builder.SetPositiveButton(Android.Resource.String.Ok, (dlgSender, dlgEvt) => { ((AlertDialog)dlgSender).Dismiss(); });
            builder.SetCancelable(false);

            WebView wv = new WebView(ctx);

            wv.SetBackgroundColor(Color.White);
            wv.LoadDataWithBaseURL(null, GetLog(changeLog, warning, ctx), "text/html", "UTF-8", null);


            //builder.SetMessage("");
            builder.SetView(wv);
            Dialog dialog = builder.Create();

            dialog.DismissEvent += (sender, e) =>
            {
                onDismiss();
            };
            dialog.Show();

            /*TextView message = (TextView)dialog.FindViewById(Android.Resource.Id.Message);
             *
             *
             * message.TextFormatted = Html.FromHtml(ConcatChangeLog(ctx, changeLog.ToArray()));
             * message.AutoLinkMask=MatchOptions.WebUrls;*/
        }
Пример #38
0
 private void spawnFilterDialog()
 {
     selectedItems.Add(0);
     selectedItems.Add(1);
     selectedItems.Add(2);
     var builder = new AlertDialog.Builder(ViewContext)
         .SetTitle("Filter Events")
         .SetMultiChoiceItems(items, new bool[] {true,true,true}, MultiListClicked);
     builder.SetPositiveButton("Ok", OkClicked);
     builder.Create();
     builder.Show();
 }
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            _view = inflater.Inflate(Resource.Layout.historical_description, container, false);
            //return base.OnCreateView(inflater, container, savedInstanceState);

            _view.FindViewById <CheckBox>(Resource.Id.checkBoxReasonFoundation).CheckedChange += (sender, e) =>
            {
                _view.FindViewById <EditText>(Resource.Id.editTextFoundingReasonOthers).Enabled = e.IsChecked;
            };
            _view.FindViewById <CheckBox>(Resource.Id.checkBoxCausesEthnic).CheckedChange += (sender, e) =>
            {
                _view.FindViewById <EditText>(Resource.Id.textInputEditTextEthnicsInTabanca).Enabled = e.IsChecked;
            };
            _view.FindViewById <CheckBox>(Resource.Id.checkBoxCausesCommunity).CheckedChange += (sender, e) =>
            {
                _view.FindViewById <EditText>(Resource.Id.textInputEditTextNearCommunity).Enabled = e.IsChecked;
            };

            var buttonAddEthnic = _view.FindViewById <Button>(Resource.Id.buttonAddEtnia);

            buttonAddEthnic.Click += (sender, e) =>
            {
                var newTabanca = CreateTabancaActivity.NewTabanca;
                _countMainEthnic++;

                if (_countMainEthnic == 3)
                {
                    buttonAddEthnic.Enabled = false;
                }

                newTabanca.MainEthnicGroupsInTabanca = newTabanca.MainEthnicGroupsInTabanca ?? new List <string>();
                var    spinner = View.FindViewById <Spinner>(Resource.Id.spinner1);
                int    index   = spinner.SelectedItemPosition;
                string item    = (string)spinner.Adapter.GetItem(index);
                if (newTabanca.MainEthnicGroupsInTabanca.Contains(item) == false)
                {
                    newTabanca.MainEthnicGroupsInTabanca.Add(item);
                    // display messsage new item added
                    var dialogBuilder = new AlertDialog.Builder(Activity, Android.Resource.Style.ThemeMaterialDialogAlert);
                    dialogBuilder.SetTitle("Etnia adicionada!");
                    dialogBuilder.SetMessage("Etnia adicionada com sucesso!");
                    dialogBuilder.SetIcon(Android.Resource.Drawable.IcDialogInfo);
                    dialogBuilder.Show();
                }
                else
                {
                    // display message item already added
                    var dialogBuilder = new AlertDialog.Builder(Activity, Android.Resource.Style.ThemeMaterialDialogAlert);
                    dialogBuilder.SetTitle("Informacao");
                    dialogBuilder.SetMessage("A etnia ja foi adicionada!");
                    dialogBuilder.SetIcon(Android.Resource.Drawable.IcDialogInfo);
                    dialogBuilder.Show();
                }
            };

            _view.FindViewById <Button>(Resource.Id.buttonAddChief).Click += (sender, e) =>
            {
                var newTabanca = CreateTabancaActivity.NewTabanca;

                newTabanca.CurrentTabancaChiefs = newTabanca.CurrentTabancaChiefs ?? new List <string>();
                var inputText = View.FindViewById <TextInputEditText>(Resource.Id.textInputEditTextCurrentChiefs);

                // invalid name
                if (string.IsNullOrWhiteSpace(inputText.Text))
                {
                    // todo: more checks
                    // display messsage new item added
                    var dialogBuilder = new AlertDialog.Builder(Activity, Android.Resource.Style.ThemeMaterialDialogAlert);
                    dialogBuilder.SetTitle("Invalido!");
                    dialogBuilder.SetMessage("Nome invalido!");
                    dialogBuilder.SetIcon(Android.Resource.Drawable.StatNotifyError);
                    dialogBuilder.Show();
                    return;
                }

                if (newTabanca.CurrentTabancaChiefs.Contains(inputText.Text) == false)
                {
                    newTabanca.CurrentTabancaChiefs.Add(inputText.Text);
                    // display messsage new item added
                    var dialogBuilder = new AlertDialog.Builder(Activity, Android.Resource.Style.ThemeMaterialDialogAlert);
                    dialogBuilder.SetTitle("Adicionar chefe!");
                    dialogBuilder.SetMessage("Chefe da tabanca adicionada com sucesso!");
                    dialogBuilder.SetIcon(Android.Resource.Drawable.IcDialogInfo);
                    dialogBuilder.Show();
                }
                else
                {
                    // display message item already added
                    var dialogBuilder = new AlertDialog.Builder(Activity, Android.Resource.Style.ThemeMaterialDialogAlert);
                    dialogBuilder.SetTitle("Informacao");
                    dialogBuilder.SetMessage("Chefe da tabanca com o mesmo nome ja existe!");
                    dialogBuilder.SetIcon(Android.Resource.Drawable.IcDialogInfo);
                    dialogBuilder.Show();
                }
            };

            LoadState();

            return(_view);
        }
        private void MAdapter_ItemDelete(object sender, int e)
        {
            string nazivLokacije = db.Query <DID_Lokacija>(
                "SELECT * " +
                "FROM DID_Lokacija " +
                "WHERE SAN_Id = ?", lokacijaId).FirstOrDefault().SAN_Naziv;

            List <DID_Potvrda> potvrda = db.Query <DID_Potvrda>(
                "SELECT * " +
                "FROM DID_Potvrda " +
                "WHERE Lokacija = ? " +
                "AND RadniNalog = ?", lokacijaId, radniNalogId);

            int statusLokacije = db.Query <DID_RadniNalog_Lokacija>(
                "SELECT * " +
                "FROM DID_RadniNalog_Lokacija " +
                "WHERE Lokacija = ? " +
                "AND RadniNalog = ?", lokacijaId, radniNalogId).FirstOrDefault().Status;

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.SetTitle("Potvrda");
            if (potvrda.Any())
            {
                alert.SetMessage("Lokacija " + nazivLokacije + " je zaključana. Jeste li sigurni da želite obrisati materijal?");
                alert.SetPositiveButton("OBRIŠI", (senderAlert, arg) =>
                {
                    DeleteMaterijal(filtriranePotrosnje[e]);

                    db.Execute(
                        "DELETE FROM DID_Potvrda_Materijal " +
                        "WHERE Potvrda = ?", potvrda.FirstOrDefault().Id);

                    db.Execute(
                        "INSERT INTO DID_Potvrda_Materijal (Potvrda, Materijal, Utroseno, MaterijalNaziv) " +
                        "SELECT pot.Id, mat.MaterijalSifra, TOTAL(mat.Kolicina), mat.MaterijalNaziv " +
                        "FROM DID_AnketaMaterijali mat " +
                        "INNER JOIN DID_LokacijaPozicija poz ON poz.POZ_Id = mat.PozicijaId " +
                        "INNER JOIN DID_Potvrda pot ON pot.RadniNalog = mat.RadniNalog " +
                        "AND pot.Lokacija = poz.SAN_Id " +
                        "WHERE pot.Id = ? " +
                        "GROUP BY mat.MaterijalSifra, mat.MjernaJedinica", potvrda.FirstOrDefault().Id);

                    var listaMaterijalaPotvrda = db.Query <DID_Potvrda_Materijal>("SELECT * FROM DID_Potvrda_Materijal WHERE Potvrda = ?", potvrda.FirstOrDefault().Id);

                    foreach (var materijal in listaMaterijalaPotvrda)
                    {
                        db.Execute(
                            "UPDATE DID_Potvrda_Materijal " +
                            "SET SinhronizacijaPrivremeniKljuc = ? " +
                            "WHERE Id = ?", materijal.Id, materijal.Id);
                    }

                    intent = new Intent(this, typeof(Activity_PotroseniMaterijali));
                    StartActivity(intent);
                });

                alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { });
                Dialog dialog = alert.Create();
                dialog.Show();
            }
            else
            {
                alert.SetMessage("Jeste li sigurni da želite obrisati materijal?");
                alert.SetPositiveButton("OBRIŠI", (senderAlert, arg) =>
                {
                    DeleteMaterijal(filtriranePotrosnje[e]);
                    intent = new Intent(this, typeof(Activity_PotroseniMaterijali));
                    StartActivity(intent);
                });

                alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { });
                Dialog dialog = alert.Create();
                dialog.Show();
            }
        }
Пример #41
0
        public static void ShowFilenameDialog(Activity activity, Func <string, Dialog, bool> onOpen, Func <string, Dialog, bool> onCreate, Action onCancel, bool showBrowseButton, string defaultFilename, string detailsText, int requestCodeBrowse)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.SetView(activity.LayoutInflater.Inflate(Resource.Layout.file_selection_filename, null));

            if (onCancel != null)
            {
                builder.SetOnCancelListener(new CancelListener(onCancel));
            }
            Dialog dialog = builder.Create();

            dialog.Show();

            Button openButton   = (Button)dialog.FindViewById(Resource.Id.open);
            Button createButton = (Button)dialog.FindViewById(Resource.Id.create);

            TextView enterFilenameDetails = (TextView)dialog.FindViewById(Resource.Id.label_open_by_filename_details);

            openButton.Visibility   = onOpen != null ? ViewStates.Visible : ViewStates.Gone;
            createButton.Visibility = onCreate != null? ViewStates.Visible : ViewStates.Gone;
            // Set the initial value of the filename
            EditText editFilename = (EditText)dialog.FindViewById(Resource.Id.file_filename);

            editFilename.Text               = defaultFilename;
            enterFilenameDetails.Text       = detailsText;
            enterFilenameDetails.Visibility = enterFilenameDetails.Text == "" ? ViewStates.Gone : ViewStates.Visible;

            // Open button
            if (onOpen != null)
            {
                openButton.Click += (sender, args) =>
                {
                    String fileName = ((EditText)dialog.FindViewById(Resource.Id.file_filename)).Text;
                    if (onOpen(fileName, dialog))
                    {
                        dialog.Dismiss();
                    }
                }
            }
            ;

            // Create button
            if (onCreate != null)
            {
                createButton.Click += (sender, args) =>
                {
                    String fileName = ((EditText)dialog.FindViewById(Resource.Id.file_filename)).Text;
                    if (onCreate(fileName, dialog))
                    {
                        dialog.Dismiss();
                    }
                }
            }
            ;

            Button cancelButton = (Button)dialog.FindViewById(Resource.Id.fnv_cancel);

            cancelButton.Click += delegate
            {
                dialog.Dismiss();
                if (onCancel != null)
                {
                    onCancel();
                }
            };

            ImageButton browseButton = (ImageButton)dialog.FindViewById(Resource.Id.browse_button);

            if (!showBrowseButton)
            {
                browseButton.Visibility = ViewStates.Invisible;
            }
            browseButton.Click += (sender, evt) =>
            {
                string filename = ((EditText)dialog.FindViewById(Resource.Id.file_filename)).Text;

                Util.ShowBrowseDialog(activity, requestCodeBrowse, onCreate != null, /*TODO should we prefer ActionOpenDocument here?*/ false);
            };
        }
Пример #42
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Main);

            // Get data from caller activity
            var json = Intent.GetStringExtra("CARDS") ?? "N/A";

            Log.Debug(TAG, "Data received: " + json);

            // Initialize and configure Text2speech engine
            tts = new TextToSpeech(this, this);
            var ttsEngines = tts.Engines;
            var ec         = ttsEngines.Count;

            Log.Debug(TAG, "Installed TTS engines: " + ec);
            foreach (var e in ttsEngines)
            {
                Log.Debug(TAG, "Engine name: " + e.Name);
                Log.Debug(TAG, "Engine label: " + e.Label);
            }

            if (ec > 0)
            {
                // configure TTS engine
                tts.SetPitch(1.0f);
                tts.SetSpeechRate(1.0f);
            }
            else
            {
                var ad = new AlertDialog.Builder(this);
                ad.SetTitle("Warning!");
                ad.SetMessage("No TextToSpeech engines detected." + System.Environment.NewLine + "Install a TTS engine and restart this application!");
                ad.SetPositiveButton("OK", (sender, e) => { });
                ad.Show();
            }

            // configure viewpager
            vpa   = new VPAdapter(this, json);
            pager = FindViewById <ViewPager>(Resource.Id.pager);
            pager.SetBackgroundResource(Resource.Drawable.PagerStyle);
            pager.Adapter = vpa;

            // configure PagerTabStrip
            var pts = pager.FindViewById <PagerTabStrip>(Resource.Id.pts);

            pts.SetBackgroundResource(Resource.Drawable.TabStripStyle);

            // get button and set click event handler
            var btnAddPic = FindViewById <Button>(Resource.Id.btnAddPic);

            btnAddPic.Click += (sender, e) =>
            {
                if (vpa.Count < maxImages)
                {
                    var i = new Intent();
                    i.SetType("image/*");
                    i.SetAction(Intent.ActionGetContent);
                    StartActivityForResult(Intent.CreateChooser(i, "Pick an image..."), RC);
                }
                else
                {
                    Toast.MakeText(this, "Maximum allowed images: " + maxImages, ToastLength.Short).Show();
                }
            };
        }
Пример #43
0
		/// <summary>
		/// Shows alert dialog.
		/// </summary>
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: private void showAlertDialog(String message, final boolean finishActivity)
		private void showAlertDialog(string message, bool finishActivity)
		{

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setMessage(message).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Alert").setPositiveButton([email protected], new OnClickListenerAnonymousInnerClassHelper(this, finishActivity, dialog))
				   .Cancelable = false;

			runOnUiThread(() =>
			{
				dialog.show();
			});
		}
Пример #44
0
			public OnClickListenerAnonymousInnerClassHelper3(Sample_Filter outerInstance, bool finishActivity, AlertDialog.Builder dialog)
			{
				this.outerInstance = outerInstance;
				this.finishActivity = finishActivity;
				this.dialog = dialog;
			}