Exemple #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);
        }
        /// <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;
            });
        }
Exemple #3
0
        private async void Redirect()
        {
            var intent = new Intent();

            intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);

            var guid = PreferenceManager.GetDefaultSharedPreferences(this).GetString("guid", "vazio");

            if (guid.Equals("vazio"))
            {
                await System.Threading.Tasks.Task.Delay(1500);

                intent.SetClass(this, typeof(UnlockActivity));
                StartActivity(intent);
                Finish();
            }
            else
            {
                var t = new Thread(new ThreadStart(delegate
                {
                    var res = Request.GetInstance().Post <System.Object>("authentication", "validate", "", new HttpParam("device_guid", guid));
                    RunOnUiThread(() =>
                    {
                        if (res.status == null)
                        {
#if DEBUG
                            AlertDialog.Builder alerta = new AlertDialog.Builder(this);
                            alerta.SetTitle("Debug");
                            alerta.SetMessage(res.debug);
                            alerta.SetPositiveButton("Fechar", (sender, e) => { Finish(); });
                            alerta.Show();
                            return;
#else
                            AlertDialog.Builder alerta = new AlertDialog.Builder(this);
                            alerta.SetTitle("Aviso");
                            alerta.SetMessage("Erro no servidor. O Aplicativo será fechado, tente novamente mais tarde.");
                            alerta.SetPositiveButton("Fechar", (sender, e) => { Finish(); });
                            alerta.Show();
                            return;
#endif
                        }

                        if (res.status.code == 200)
                        {
                            intent.SetClass(this, typeof(LoginActivity));
                        }
                        else
                        {
                            var editor = PreferenceManager.GetDefaultSharedPreferences(this).Edit();
                            editor.Remove("guid");
                            editor.Remove("authentication");
                            editor.Commit();

                            intent.SetClass(this, typeof(UnlockActivity));
                        }

                        StartActivity(intent);
                        Finish();
                    });
                }));
                t.Start();
            }
        }
Exemple #4
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            //注册控件
            EditText txt_writeKey   = FindViewById <EditText>(Resource.Id.txt_WriteKey);
            EditText txt_writeValue = FindViewById <EditText>(Resource.Id.txt_WriteValue);
            EditText txt_ReadKey    = FindViewById <EditText>(Resource.Id.txt_ReadKey);
            Button   btn_Write      = FindViewById <Button>(Resource.Id.btn_Write);
            Button   btn_Read       = FindViewById <Button>(Resource.Id.btn_Read);

            //点击按钮
            btn_Write.Click += (o, e) =>
            {
                if (txt_writeKey.Text == "")
                {
                    Toast.MakeText(this, "请输入要写入的Key", ToastLength.Short).Show();
                    return;
                }
                if (txt_writeValue.Text == "")
                {
                    Toast.MakeText(this, "请输入要写入的Value", ToastLength.Short).Show();
                    return;
                }
                CreateTable();
                int count = 0;
                count = SqliteHelper.ExecuteScalarNum("select count(key) from test where key=@key",
                                                      "@key=" + txt_writeKey.Text);
                if (count > 0)
                {
                    Toast.MakeText(this, "Key:" + txt_writeKey.Text + " 已存在,不允许重复", ToastLength.Short).Show();
                    return;
                }
                count = SqliteHelper.ExecuteNonQuery("insert into test(key,value)values (@key,@value)",
                                                     "@key=" + txt_writeKey.Text,
                                                     "@value=" + txt_writeValue.Text);
                if (count > 0)
                {
                    txt_writeKey.Text   = "";
                    txt_writeValue.Text = "";
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("提示:");
                    builder.SetMessage("写入成功\n");
                    builder.SetPositiveButton("确定", delegate { });
                    builder.SetNegativeButton("取消", delegate { });
                    builder.Show();
                }
                else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("提示:");
                    builder.SetMessage("写入失败\n" + SqliteHelper.SqlErr);
                    builder.SetPositiveButton("确定", delegate { });
                    builder.SetNegativeButton("取消", delegate { });
                    builder.Show();
                }
            };
            btn_Read.Click += (o, e) =>
            {
                if (txt_ReadKey.Text == "")
                {
                    Toast.MakeText(this, "请输入要读取的Key", ToastLength.Short).Show();
                    return;
                }
                string value = SqliteHelper.ExecuteScalar("select value from test where key=@key",
                                                          "@key=" + txt_ReadKey.Text);
                if (string.IsNullOrEmpty(value))
                {
                    Toast.MakeText(this, "Key:" + txt_ReadKey.Text + " 不存在,清先写入该Key", ToastLength.Short).Show();
                    return;
                }
                txt_ReadKey.Text = "";
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetTitle("提示:");
                builder.SetMessage("Key:" + txt_ReadKey.Text + " 对应的value为\n" + value);
                builder.SetPositiveButton("确定", delegate { });
                builder.SetNegativeButton("取消", delegate { });
                builder.Show();
            };
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            var    FooterText = FindViewById <TextView>(Resource.Id.footerText);
            string version    = PackageManager.GetPackageInfo(PackageName, 0).VersionName;

            FooterText.Text    = $"InstaShit.Android v{version} - Created by Konrad Krawiec";
            StatusText         = FindViewById <TextView>(Resource.Id.statusTextView);
            StartButton        = FindViewById <Button>(Resource.Id.startButton);
            ProgressBar        = FindViewById <ProgressBar>(Resource.Id.progressBar);
            AnswerCountText    = FindViewById <TextView>(Resource.Id.answerCountText);
            LogButton          = FindViewById <Button>(Resource.Id.logButton);
            SettingsButton     = FindViewById <Button>(Resource.Id.settingsButton);
            _receiver          = new Receiver();
            _receiver.Activity = this;
            if (savedInstanceState != null)
            {
                StatusText.Text = savedInstanceState.GetString("statusText", "Status: Stopped");
            }
            if (StatusText.Text == "Status: Stopped")
            {
                StartButton.Text          = "Start InstaShit";
                StartButton.Enabled       = true;
                ProgressBar.Indeterminate = false;
                ProgressBar.Progress      = 0;
            }
            else if (StatusText.Text == "Status: Running")
            {
                StartButton.Text           = "Stop InstaShit";
                StartButton.Enabled        = true;
                ProgressBar.Indeterminate  = true;
                SettingsButton.Enabled     = false;
                AnswerCountText.Visibility = Android.Views.ViewStates.Visible;
            }
            else if (StatusText.Text == "Status: Stopping")
            {
                StartButton.Text           = "Stopping...";
                StartButton.Enabled        = false;
                SettingsButton.Enabled     = false;
                ProgressBar.Indeterminate  = true;
                AnswerCountText.Visibility = Android.Views.ViewStates.Visible;
            }
            else if (StatusText.Text == "Status: Finished")
            {
                StartButton.Text          = "Start InstaShit";
                StartButton.Enabled       = true;
                StatusText.Text           = "Status: Stopped";
                ProgressBar.Indeterminate = false;
                ProgressBar.Progress      = 100;
            }
            AnswerCountText.Text = "Answered questions: " + Counter;
            LogButton.Click     += (sender, e) =>
            {
                var intent = new Intent(this, typeof(LogActivity));
                intent.PutStringArrayListExtra("log", Log);
                StartActivity(intent);
            };
            SettingsButton.Click += (sender, e) =>
            {
                var intent = new Intent(this, typeof(SettingsActivity));
                StartActivity(intent);
            };
            StartButton.Click += (sender, e) =>
            {
                if (StartButton.Text == "Start InstaShit")
                {
                    Log.Clear();
                    if (!File.Exists(GetFileLocation("settings.json")))
                    {
                        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                        alertBuilder.SetTitle("Error");
                        alertBuilder.SetMessage("The settings file doesn't exist. Do you want to create it now?");
                        alertBuilder.SetPositiveButton("Yes", (senderAlert, args) =>
                        {
                            var intent = new Intent(this, typeof(SettingsActivity));
                            StartActivity(intent);
                        });
                        alertBuilder.SetNegativeButton("No", (senderAlert, args) =>
                        {
                        });
                        var dialog = alertBuilder.Create();
                        dialog.Show();
                        Log.Add("Can't find settings file!");
                        return;
                    }
                    InstaShitService.ShouldContinue = true;
                    StartButton.Text          = "Stop InstaShit";
                    StatusText.Text           = "Status: Running";
                    SettingsButton.Enabled    = false;
                    ProgressBar.Indeterminate = true;
                    Intent instaShitIntent = new Intent(this, typeof(InstaShitService));
                    Counter = 0;
                    AnswerCountText.Text       = "Answered questions: " + Counter;
                    AnswerCountText.Visibility = Android.Views.ViewStates.Visible;
                    StartService(instaShitIntent);
                }
                else
                {
                    InstaShitService.ShouldContinue = false;
                    StatusText.Text     = "Status: Stopping";
                    StartButton.Text    = "Stopping...";
                    StartButton.Enabled = false;
                }
            };
            LocalBroadcastManager.GetInstance(this).RegisterReceiver(_receiver, new IntentFilter("com.InstaShit.Android.INFORMATION"));
        }
Exemple #6
0
 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();
 }
Exemple #7
0
        public void CreatePopup(object sender, RatingBar.RatingBarChangeEventArgs e)
        {
            if (CurrentUser.getUserId() == null || CurrentUser.getUserId() == "0")
            {
                AlertDialog.Builder aler = new AlertDialog.Builder(Parent, Resource.Style.MyDialogTheme);
                aler.SetTitle("Sorry");
                aler.SetMessage("This Feature is available for VIP Users only");
                aler.SetNegativeButton("Ok", delegate {
                });
                Dialog dialog1 = aler.Create();
                dialog1.Show();
            }
            else
            {
                try
                {
                    Dialog editDialog = new Dialog(Parent);
                    var    rat        = e.Rating;
                    editDialog.SetContentView(Resource.Layout.EditReviewPopup);
                    ServiceWrapper sw              = new ServiceWrapper();
                    Review         review          = new Review();
                    ImageButton    close           = editDialog.FindViewById <ImageButton>(Resource.Id.close);
                    Button         btnSubmitReview = editDialog.FindViewById <Button>(Resource.Id.btnSubmitReview);
                    TextView       Comments        = editDialog.FindViewById <TextView>(Resource.Id.txtReviewComments);
                    RatingBar      custRating      = editDialog.FindViewById <RatingBar>(Resource.Id.rating);
                    custRating.Rating = rat;
                    Comments.Text     = _editObj.RatingText;
                    int screenid = 9;
                    close.SetScaleType(ImageView.ScaleType.CenterCrop);
                    editDialog.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.Transparent));
                    editDialog.Show();
                    editDialog.SetCanceledOnTouchOutside(false);
                    LoggingClass.LogInfo("Entered into CreatePopup", screenid);

                    close.Click += delegate
                    {
                        LoggingClass.LogInfo("Closed PoPup", screenid);
                        editDialog.Dismiss();
                    };
                    btnSubmitReview.Click += async delegate
                    {
                        AndHUD.Shared.Show(Parent, "Saving Review...", Convert.ToInt32(MaskType.Clear));
                        //  ProgressIndicator.Show(Parent);
                        review.ReviewDate   = DateTime.Now;
                        review.ReviewUserId = Convert.ToInt32(CurrentUser.getUserId());
                        review.Username     = CurrentUser.getUserName();
                        review.RatingText   = Comments.Text;
                        review.RatingStars  = Convert.ToInt32(custRating.Rating);
                        review.IsActive     = true;
                        review.Barcode      = WineBarcode;
                        review.PlantFinal   = storeid;
                        LoggingClass.LogInfo("Submitted review---->" + review.RatingStars + " ---->" + review.RatingText + "---->" + review.PlantFinal + "---->" + review.Barcode, screenid);
                        await sw.InsertUpdateReview(review);

                        ((IPopupParent)Parent).RefreshParent();
                        ProgressIndicator.Hide();
                        editDialog.Dismiss();
                        AndHUD.Shared.Dismiss();
                        AndHUD.Shared.ShowSuccess(Parent, "Sucessfully Saved", MaskType.Clear, TimeSpan.FromSeconds(2));
                    };
                }
                catch (Exception exe)
                {
                    LoggingClass.LogError(exe.Message, ParentScreenId, exe.StackTrace.ToString());
                }
            }
        }
Exemple #8
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            //// BACKGROUND SERVICE////////////////////////////
            if (ApplicationContext.StartService(new Intent(this, typeof(SimpleServiceBinder))) != null)
            {
            }
            else
            {
                ApplicationContext.StartService(new Intent(this, typeof(SimpleServiceBinder)));
            }
            ///////////////////////////////////////////////////
            /// Check internet access/////////////////////////////////////////////////////////////////////////
            bool   google_network_ok;
            string google_urlAddress = "http://google.com";

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(google_urlAddress);
                request.Timeout = 3000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream       receiveStream = response.GetResponseStream();
                    StreamReader readStream    = null;

                    if (response.CharacterSet == null)
                    {
                        readStream = new StreamReader(receiveStream);
                    }
                    else
                    {
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                    }

                    data = readStream.ReadToEnd();

                    response.Close();
                    readStream.Close();
                }
                google_network_ok = true;
            }
            catch (WebException ex)
            {
                google_network_ok = false;
            }
            //store data
            var prefs = Application.Context.GetSharedPreferences("KiedyTest", FileCreationMode.Private);

            var first_launch = prefs.GetString("first_launch", null);
            var logged       = prefs.GetString("logged", null);
            var prefEditor   = prefs.Edit();

            if (first_launch != "no")
            {
                prefEditor.PutString("first_launch", "no");
                prefEditor.PutInt("connection_timeout", 3000);
                prefEditor.PutString("heartbeat_enabled", "yes");
                prefEditor.PutString("notify_enabled", "yes");
                prefEditor.Commit();
            }

            if (logged == "yes")
            {
                var activity2 = new Intent(this, typeof(Activity2));
                StartActivity(activity2); ///  start menu activity
            }
            Button start = FindViewById <Button>(Resource.Id.MyButton);

            start.Click += delegate {
                /// LOGIN ACTION///
                // Request ///
                string content, content2;
                bool   network_ok;

                if (google_network_ok)
                {
                    var    et1           = FindViewById <EditText>(Resource.Id.editText3);
                    var    user_name     = et1.Text;
                    var    et2           = FindViewById <EditText>(Resource.Id.editText2);
                    var    user_password = et2.Text;
                    string urlAddress    = "http://dziennik.zs1debica.pl/kiedytest/android/request_handler/login_app.php?user_name=" + user_name + "&user_password="******"\x00", "");  //  // AWESOME !!!!! // in my case I want to see it, otherwise just replace with ""
                        MemoryStream memStream = new MemoryStream();
                        byte[]       data2     = System.Text.Encoding.UTF8.GetBytes(content);
                        memStream.Write(data2, 0, data2.Length);
                        memStream.Position = 0;

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(content);
                        //////////////////////////////////////////////////////////////////

                        foreach (XmlElement x in doc.SelectNodes("result/result_data/auth_result"))
                        {
                            auth_result = x.InnerXml;
                        }
                        /////////////////////////////////////////////////////////////////////////////////
                        /// Converting variables//////////////////
                        int.TryParse(auth_result, out auth_result_int);
                        //////////////////////////////////////LOGIN/////////

                        if (auth_result_int == 1)
                        {
                            prefEditor.PutString("logged", "yes");
                            prefEditor.PutString("login", user_name);
                            prefEditor.PutString("password", user_password);
                            prefEditor.Commit();

                            var builder3 = new AlertDialog.Builder(this);
                            builder3.SetMessage("Zostałeś pomyślnie zalogowany");
                            //   builder3.SetPositiveButton("OK", OkAction);
                            builder3.Show();
                            var activity2 = new Intent(this, typeof(Activity2));
                            StartActivity(activity2); ///  start menu activity
                        }
                        else
                        {
                            var builder3 = new AlertDialog.Builder(this);
                            builder3.SetMessage("Login i/lub hasło jest niepoprawne! Proszę spróbować ponownie!");
                            builder3.Show();
                        }
                    }
                    else
                    {
                        var builder3 = new AlertDialog.Builder(this);
                        builder3.SetMessage("Błąd połaczenia z serwerami KiedyTest. Proszę spróbować ponownie później");
                        builder3.Show();
                    }
                }
                else
                {
                    var builder3 = new AlertDialog.Builder(this);
                    builder3.SetMessage("Błąd łączenia z Internetem! Proszę sprawdzić swoje połączenie sieciowe!");
                    builder3.Show();
                }
            };
        }
Exemple #9
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);

            // Set a dialog title.
            Dialog.SetTitle("Define a symbol");

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

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

            dialogView.SetPadding(10, 0, 10, 10);

            try
            {
                // Create a list box for showing each category of symbol: eyes, mouth, hat.
                _eyesList  = new ListView(ctx);
                _mouthList = new ListView(ctx);
                _hatList   = new ListView(ctx);

                // Create a new list adapter to show the eye symbols in a list view.
                SymbolListAdapter eyesAdapter = new SymbolListAdapter(Activity, _eyeSymbolInfos);

                // Handle selection change events for the eyes symbol adapter.
                eyesAdapter.OnSymbolSelectionChanged += async(sender, e) =>
                {
                    // Get the key for the selected eyes (if any) then update the symbol.
                    if (eyesAdapter.SelectedSymbolInfo != null)
                    {
                        _selectedEyesKey = eyesAdapter.SelectedSymbolInfo?.Key;
                        await UpdateSymbol();
                    }
                };

                // Assign the adapter to the list view.
                _eyesList.Adapter = eyesAdapter;

                // Create a label to for the "eyes" symbol list.
                TextView eyesLabel = new TextView(ctx);
                eyesLabel.SetText("Eyes", TextView.BufferType.Normal);
                eyesLabel.Gravity  = GravityFlags.Center;
                eyesLabel.TextSize = 15.0f;
                eyesLabel.SetTextColor(Android.Graphics.Color.Black);

                // Add the eyes label and list to the dialog.
                dialogView.AddView(eyesLabel);
                dialogView.AddView(_eyesList);

                // Create a new list adapter to show the mouth symbols in a list view.
                SymbolListAdapter mouthAdapter = new SymbolListAdapter(Activity, _mouthSymbolInfos);

                // Handle selection change events for the eyes symbol adapter.
                mouthAdapter.OnSymbolSelectionChanged += async(sender, e) =>
                {
                    // Get the key for the selected mouth (if any) then update the symbol.
                    if (mouthAdapter.SelectedSymbolInfo != null)
                    {
                        _selectedMouthKey = mouthAdapter.SelectedSymbolInfo?.Key;
                        await UpdateSymbol();
                    }
                };

                // Assign the adapter to the list view.
                _mouthList.Adapter = mouthAdapter;

                // Create a label to for the "mouth" symbol list.
                TextView mouthLabel = new TextView(ctx);
                mouthLabel.SetText("Mouth", TextView.BufferType.Normal);
                mouthLabel.Gravity  = GravityFlags.Center;
                mouthLabel.TextSize = 15.0f;
                mouthLabel.SetTextColor(Android.Graphics.Color.Black);

                // Add the mouth label and list to the dialog.
                dialogView.AddView(mouthLabel);
                dialogView.AddView(_mouthList);

                // Create a new list adapter to show the hat symbols in a list view.
                SymbolListAdapter hatAdapter = new SymbolListAdapter(Activity, _hatSymbolInfos);

                // Handle selection change events for the hat symbol adapter.
                hatAdapter.OnSymbolSelectionChanged += async(sender, e) =>
                {
                    // Get the key for the selected hat (if any) then update the symbol.
                    if (hatAdapter.SelectedSymbolInfo != null)
                    {
                        _selectedHatKey = hatAdapter.SelectedSymbolInfo?.Key;
                        await UpdateSymbol();
                    }
                };

                // Assign the adapter to the list view.
                _hatList.Adapter = hatAdapter;

                // Create a label to for the "hat" symbol list.
                TextView hatLabel = new TextView(ctx);
                hatLabel.SetText("Hat", TextView.BufferType.Normal);
                hatLabel.Gravity  = GravityFlags.Center;
                hatLabel.TextSize = 15.0f;
                hatLabel.SetTextColor(Android.Graphics.Color.Black);

                // Add the hat label and list to the dialog.
                dialogView.AddView(hatLabel);
                dialogView.AddView(_hatList);

                // Add a preview image for the symbol.
                _symbolPreviewImage = new ImageView(ctx);
                dialogView.AddView(_symbolPreviewImage);

                // A button to set a yellow symbol color.
                Button yellowButton = new Button(ctx);
                yellowButton.SetBackgroundColor(Color.Yellow);

                // Handle the button click event to set the current color and update the symbol.
                yellowButton.Click += async(sender, e) =>
                {
                    _faceColor = Color.Yellow; await UpdateSymbol();
                };

                // A button to set a green symbol color.
                Button greenButton = new Button(ctx);
                greenButton.SetBackgroundColor(Color.Green);

                // Handle the button click event to set the current color and update the symbol.
                greenButton.Click += async(sender, e) =>
                {
                    _faceColor = Color.Green; await UpdateSymbol();
                };

                // A button to set a pink symbol color.
                Button pinkButton = new Button(ctx);
                pinkButton.SetBackgroundColor(Color.Pink);

                // Handle the button click event to set the current color and update the symbol.
                pinkButton.Click += async(sender, e) =>
                {
                    _faceColor = Color.Pink; await UpdateSymbol();
                };

                // Add the color selection buttons to a horizontal layout.
                LinearLayout colorLayout = new LinearLayout(ctx)
                {
                    Orientation = Orientation.Horizontal
                };
                colorLayout.SetPadding(10, 20, 10, 20);
                colorLayout.AddView(yellowButton);
                colorLayout.AddView(greenButton);
                colorLayout.AddView(pinkButton);

                // Add the color selection buttons to the dialog.
                dialogView.AddView(colorLayout);

                // Create a slider (SeekBar) to adjust the symbol size.
                SeekBar sizeSlider = new SeekBar(ctx)
                {
                    // Set a maximum slider value of 60 and a current value of 20.
                    Max      = 60,
                    Progress = 20
                };

                // Create a label to show the selected symbol size (preview size won't change).
                TextView sizeLabel = new TextView(ctx)
                {
                    Gravity  = GravityFlags.Right,
                    TextSize = 10.0f,
                    Text     = $"Size:{_symbolSize:0}"
                };
                sizeLabel.SetTextColor(Color.Black);

                // When the slider value (Progress) changes, update the symbol with the new size.
                sizeSlider.ProgressChanged += (s, e) =>
                {
                    // Read the slider value and limit the minimum size to 8.
                    _symbolSize = (e.Progress < 8) ? 8 : e.Progress;

                    // Show the selected size in the label.
                    sizeLabel.Text = $"Size:{_symbolSize:0}";
                };

                // Create a horizontal layout to show the slider and label.
                LinearLayout sliderLayout = new LinearLayout(ctx)
                {
                    Orientation = Orientation.Horizontal
                };
                sliderLayout.SetPadding(10, 10, 10, 10);
                sizeSlider.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, 1.0f);

                // Add the size slider and label to the layout.
                sliderLayout.AddView(sizeSlider);
                sliderLayout.AddView(sizeLabel);

                // Add the size controls to the dialog layout.
                dialogView.AddView(sliderLayout);

                // Add a button to close the dialog and use the current symbol.
                Button selectSymbolButton = new Button(ctx)
                {
                    Text = "OK"
                };

                // Handle the button click to dismiss the dialog and pass back the symbol.
                selectSymbolButton.Click += SelectSymbolButtonClick;

                // Add the button to the dialog.
                dialogView.AddView(selectSymbolButton);
            }
            catch (Exception ex)
            {
                // Show the exception message.
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Activity);
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }

            // Show a preview of the current symbol (created previously or the default face).
            UpdateSymbol();

            // Return the new view for display.
            return(dialogView);
        }
Exemple #10
0
        public View GetSampleContent(Context con)
        {
            ScrollView   scroll   = new ScrollView(con);
            bool         isTablet = SfMaskedEditText.IsTabletDevice(con);
            LinearLayout linear   = new LinearLayout(con);

            linear.SetBackgroundColor(Color.White);
            linear.Orientation = Orientation.Vertical;
            linear.SetPadding(12, 12, 12, 12);

            TextView headLabel = new TextView(con);

            headLabel.TextSize = 30;
            headLabel.SetTextColor(Color.ParseColor("#262626"));
            headLabel.Typeface = Typeface.DefaultBold;
            headLabel.Text     = "Funds Transfer";
            linear.AddView(headLabel);

            TextView fundTransferLabelSpacing = new TextView(con);

            fundTransferLabelSpacing.SetHeight(40);
            linear.AddView(fundTransferLabelSpacing);

            TextView textToAccount = new TextView(con);

            textToAccount.SetTextColor(Color.ParseColor("#6d6d72"));
            textToAccount.TextSize = 16;
            textToAccount.Typeface = Typeface.Default;
            textToAccount.Text     = "To Account";
            textToAccount.SetPadding(0, 0, 0, 10);
            linear.AddView(textToAccount);


            sfToAccount                 = new SfMaskedEdit(con);
            sfToAccount.Mask            = "0000 0000 0000 0000";
            sfToAccount.Gravity         = GravityFlags.Start;
            sfToAccount.ValidationMode  = InputValidationMode.KeyPress;
            sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
            sfToAccount.Hint            = "1234 1234 1234 1234";
            sfToAccount.SetHintTextColor(Color.LightGray);
            linear.AddView(sfToAccount);

            erroToAccount = new TextView(con);
            erroToAccount.SetTextColor(Color.Red);
            erroToAccount.TextSize = 12;
            erroToAccount.Typeface = Typeface.Default;
            linear.AddView(erroToAccount);

            TextView textDesc = new TextView(con);

            textDesc.Text     = "Description";
            textDesc.Typeface = Typeface.Default;
            textDesc.SetPadding(0, 30, 0, 10);
            textDesc.TextSize = 16;
            linear.AddView(textDesc);


            sfDesc                 = new SfMaskedEdit(con);
            sfDesc.Mask            = "";
            sfDesc.Gravity         = GravityFlags.Start;
            sfDesc.ValidationMode  = InputValidationMode.KeyPress;
            sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
            sfDesc.Hint            = "Enter description";
            sfDesc.SetHintTextColor(Color.LightGray);
            linear.AddView(sfDesc);


            TextView textAmount = new TextView(con);

            textAmount.Text     = "Amount";
            textAmount.Typeface = Typeface.Default;
            textAmount.SetPadding(0, 30, 0, 10);
            textAmount.TextSize = 16;
            linear.AddView(textAmount);

            amountMask                 = new SfMaskedEdit(con);
            amountMask.Mask            = "$ 0,000.00";
            amountMask.Gravity         = GravityFlags.Start;
            amountMask.ValidationMode  = InputValidationMode.KeyPress;
            amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals;
            amountMask.Hint            = "$ 3,874.00";
            amountMask.SetHintTextColor(Color.LightGray);
            linear.AddView(amountMask);

            errotextAmount = new TextView(con);
            errotextAmount.SetTextColor(Color.Red);
            errotextAmount.TextSize = 12;
            errotextAmount.Typeface = Typeface.Default;
            linear.AddView(errotextAmount);


            TextView textEmail = new TextView(con);

            textEmail.Text     = "Email ID";
            textEmail.Typeface = Typeface.Default;
            textEmail.SetPadding(0, 30, 0, 10);
            textEmail.TextSize = 16;
            linear.AddView(textEmail);

            emailMask                 = new SfMaskedEdit(con);
            emailMask.Mask            = @"\w+@\w+\.\w+";
            emailMask.MaskType        = MaskType.RegEx;
            emailMask.Gravity         = GravityFlags.Start;
            emailMask.ValidationMode  = InputValidationMode.KeyPress;
            emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
            emailMask.Hint            = "*****@*****.**";
            emailMask.SetHintTextColor(Color.LightGray);
            linear.AddView(emailMask);

            errotextEmail = new TextView(con);
            errotextEmail.SetTextColor(Color.Red);
            errotextEmail.TextSize = 12;
            errotextEmail.Typeface = Typeface.Default;
            linear.AddView(errotextEmail);

            TextView textPhone = new TextView(con);

            textPhone.Text     = "Mobile Number ";
            textPhone.Typeface = Typeface.Default;
            textPhone.SetPadding(0, 30, 0, 10);
            textPhone.TextSize = 16;
            linear.AddView(textPhone);

            phoneMask                 = new SfMaskedEdit(con);
            phoneMask.Mask            = "+1 000 000 0000";
            phoneMask.Gravity         = GravityFlags.Start;
            phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals;
            phoneMask.ValidationMode  = InputValidationMode.KeyPress;
            phoneMask.Hint            = "+1 323 339 3392";
            phoneMask.SetHintTextColor(Color.LightGray);
            linear.AddView(phoneMask);

            errotextPhone = new TextView(con);
            errotextPhone.SetTextColor(Color.Red);
            errotextPhone.TextSize = 12;
            errotextPhone.Typeface = Typeface.Default;
            linear.AddView(errotextPhone);

            TextView searchButtonSpacing = new TextView(con);

            searchButtonSpacing.SetHeight(30);

            Button searchButton = new Button(con);

            searchButton.SetWidth(ActionBar.LayoutParams.MatchParent);
            searchButton.SetHeight(40);
            searchButton.Text = "TRANSFER MONEY";
            searchButton.SetTextColor(Color.White);
            searchButton.SetBackgroundColor(Color.Gray);
            searchButton.Click += (object sender, EventArgs e) =>
            {
                if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text))
                {
                    resultsDialog.SetMessage("Please fill all the required data!");
                }
                else if ((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError))
                {
                    resultsDialog.SetMessage("Please enter valid details");
                }
                else
                {
                    resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value));
                    sfToAccount.Value = string.Empty;
                    sfDesc.Value      = string.Empty;
                    amountMask.Value  = string.Empty;
                    emailMask.Value   = string.Empty;
                    phoneMask.Value   = string.Empty;
                }
                resultsDialog.Create().Show();
            };
            linear.AddView(searchButtonSpacing);
            linear.AddView(searchButton);

            sfToAccount.ValueChanged      += SfToAccount_ValueChanged;
            sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected;

            amountMask.ValueChanged      += AmountMask_ValueChanged;
            amountMask.MaskInputRejected += AmountMask_MaskInputRejected;

            emailMask.ValueChanged      += EmailMask_ValueChanged;
            emailMask.MaskInputRejected += EmailMask_MaskInputRejected;

            phoneMask.ValueChanged      += PhoneMask_ValueChanged;
            phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected;

            //results dialog
            resultsDialog = new AlertDialog.Builder(con);
            resultsDialog.SetTitle("Status");
            resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) =>
            {
            });

            resultsDialog.SetCancelable(true);

            scroll.AddView(linear);

            return(scroll);
        }
Exemple #11
0
        void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            var listView = sender as ListView;
            var t        = tableItems [e.Position];

            if (t.ClientName.Trim() != "")
            {
                if (projectid != Convert.ToInt64(t.ProjectID))
                {
                    editor.PutString("LocationName", "");
                }
                editor.PutLong("ProjectID", Convert.ToInt64(t.ProjectID));
                editor.PutString("ProjectName", t.Projectname);
                editor.PutString("ClientName", t.ClientName);
                editor.PutString("EditFromItemList", "");
                editor.PutString("EditFromItemListForBarcode", "");
                editor.PutInt("FromVoiceEdit", 0);
                editor.Commit();
                // applies changes synchronously on older APIs
                editor.Apply();
                InventoryType = prefs.GetLong("InventoryType", 0);
                if (InventoryType > 0)
                {
                    ICursor c1 = db.RawQuery("SELECT * FROM " + "tbl_Inventory WHERE ProjectID = " + t.ProjectID, null);
                    try{
                        if (c1.Count > 0)
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.SetMessage("Please select from the following options");
                            builder.SetCancelable(false);
                            builder.SetPositiveButton("Location List", (object buildersender, DialogClickEventArgs ev) => {
                                StartActivity(typeof(LocationList));
                            });
                            builder.SetNegativeButton("Add Item", (object buildersender, DialogClickEventArgs ev) => {
                                this.Finish();
                                StartActivity(typeof(EntryTab));
                            });
                            AlertDialog alertdialog = builder.Create();
                            alertdialog.Show();
                        }
                        else
                        {
                            this.Finish();
                            StartActivity(typeof(EntryTab));
                        }
                    }
                    catch {
                        Toast.MakeText(this, "Something error happend. Pls try again later", ToastLength.Short).Show();
                    }
                }
                else
                {
                    ICursor c1 = db.RawQuery("SELECT * FROM " + "tbl_Inventory WHERE ProjectID = " + t.ProjectID, null);
                    try{
                        editor = prefs.Edit();
                        editor.PutLong("InventoryType", 1);
                        editor.Commit();
                        if (c1.Count > 0)
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.SetMessage("Please select from the following options");
                            builder.SetCancelable(false);
                            builder.SetPositiveButton("Location List", (object buildersender, DialogClickEventArgs ev) => {
                                StartActivity(typeof(LocationList));
                            });
                            builder.SetNegativeButton("Add Item", (object buildersender, DialogClickEventArgs ev) => {
                                this.Finish();
                                StartActivity(typeof(EntryTab));
                            });
                            AlertDialog alertdialog = builder.Create();
                            alertdialog.Show();
                        }
                        else
                        {
                            this.Finish();
                            StartActivity(typeof(EntryTab));
                        }
                    }
                    catch {
                        Toast.MakeText(this, "Something error happend. Pls try again later", ToastLength.Short).Show();
                    }
                }
            }
            //dialog.Dismiss();
            //Android.Widget.Toast.MakeText(this, t.Projectname, Android.Widget.ToastLength.Short).Show();
        }
Exemple #12
0
        public Task <string> DisplayPromptAync(string title         = null, string description  = null,
                                               string text          = null, string okButtonText = null, string cancelButtonText = null,
                                               bool numericKeyboard = false, bool autofocus     = true, bool password           = false)
        {
            var activity = (MainActivity)CrossCurrentActivity.Current.Activity;

            if (activity == null)
            {
                return(Task.FromResult <string>(null));
            }

            var alertBuilder = new AlertDialog.Builder(activity);

            alertBuilder.SetTitle(title);
            alertBuilder.SetMessage(description);
            var input = new EditText(activity)
            {
                InputType = InputTypes.ClassText
            };

            if (text == null)
            {
                text = string.Empty;
            }
            if (numericKeyboard)
            {
                input.InputType = InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned;
#pragma warning disable CS0618 // Type or member is obsolete
                input.KeyListener = DigitsKeyListener.GetInstance(false, false);
#pragma warning restore CS0618 // Type or member is obsolete
            }
            if (password)
            {
                input.InputType = InputTypes.TextVariationPassword | InputTypes.ClassText;
            }

            input.ImeOptions = input.ImeOptions | (ImeAction)ImeFlags.NoPersonalizedLearning |
                               (ImeAction)ImeFlags.NoExtractUi;
            input.Text = text;
            input.SetSelection(text.Length);
            var container = new FrameLayout(activity);
            var lp        = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent,
                                                          LinearLayout.LayoutParams.MatchParent);
            lp.SetMargins(25, 0, 25, 0);
            input.LayoutParameters = lp;
            container.AddView(input);
            alertBuilder.SetView(container);

            okButtonText     = okButtonText ?? AppResources.Ok;
            cancelButtonText = cancelButtonText ?? AppResources.Cancel;
            var result = new TaskCompletionSource <string>();
            alertBuilder.SetPositiveButton(okButtonText,
                                           (sender, args) => result.TrySetResult(input.Text ?? string.Empty));
            alertBuilder.SetNegativeButton(cancelButtonText, (sender, args) => result.TrySetResult(null));

            var alert = alertBuilder.Create();
            alert.Window.SetSoftInputMode(Android.Views.SoftInput.StateVisible);
            alert.Show();
            if (autofocus)
            {
                input.RequestFocus();
            }
            return(result.Task);
        }
Exemple #13
0
        public Task <string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons)
        {
            var activity = (MainActivity)CrossCurrentActivity.Current.Activity;

            if (activity == null)
            {
                return(Task.FromResult <string>(null));
            }

            var result       = new TaskCompletionSource <string>();
            var alertBuilder = new AlertDialog.Builder(activity);

            alertBuilder.SetTitle(title);

            if (!string.IsNullOrWhiteSpace(message))
            {
                if (buttons != null && buttons.Length > 2)
                {
                    if (!string.IsNullOrWhiteSpace(title))
                    {
                        alertBuilder.SetTitle($"{title}: {message}");
                    }
                    else
                    {
                        alertBuilder.SetTitle(message);
                    }
                }
                else
                {
                    alertBuilder.SetMessage(message);
                }
            }

            if (buttons != null)
            {
                if (buttons.Length > 2)
                {
                    alertBuilder.SetItems(buttons, (sender, args) =>
                    {
                        result.TrySetResult(buttons[args.Which]);
                    });
                }
                else
                {
                    if (buttons.Length > 0)
                    {
                        alertBuilder.SetPositiveButton(buttons[0], (sender, args) =>
                        {
                            result.TrySetResult(buttons[0]);
                        });
                    }
                    if (buttons.Length > 1)
                    {
                        alertBuilder.SetNeutralButton(buttons[1], (sender, args) =>
                        {
                            result.TrySetResult(buttons[1]);
                        });
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(cancel))
            {
                alertBuilder.SetNegativeButton(cancel, (sender, args) =>
                {
                    result.TrySetResult(cancel);
                });
            }

            var alert = alertBuilder.Create();

            alert.CancelEvent += (o, args) => { result.TrySetResult(null); };
            alert.Show();
            return(result.Task);
        }
Exemple #14
0
        void GameThreadProc()
        {
            NetworkStream stream = Sockets.client.GetStream();

            byte[]      buffer;
            AlertDialog ad = null;

            while (Sockets.client.Connected)
            {
                try
                {
                    buffer = new byte[MainActivity.MAX_LENGTH];
                    stream.Read(buffer, 0, buffer.Length);
                    string[] data = MessageParser.Split(buffer);
                    if (data.Length == 1)
                    {
                        Sockets.client.Close();
                        RunOnUiThread(delegate
                        {
                            ad = new AlertDialog.Builder(this).Create();
                            ad.SetCancelable(false); // This blocks the 'BACK' button
                            ad.SetMessage("Nie mo¿na po³¹czyæ siê z serwerem. SprawdŸ po³¹czenie z internetem.");
                            ad.SetButton("OK", delegate
                            {
                                Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                            });
                            ad.Show();
                        });
                    }
                    switch (MessageParser.ToMessageType(data[0]))
                    {
                    case MessageTypes.TurnClient:
                        RunOnUiThread(delegate { ParseCanvas(data[1]); });
                        isMyTurn = true;
                        break;

                    case MessageTypes.WinClient:
                        RunOnUiThread(delegate
                        {
                            ad = new AlertDialog.Builder(this).Create();
                            ad.SetCancelable(false);     // This blocks the 'BACK' button
                            if (data[1].Contains(nickname))
                            {
                                ad.SetMessage("Gratulacje! Wygra³eœ!");
                            }
                            else
                            {
                                ad.SetMessage("Niestety przegra³eœ!");
                            }
                            ad.SetButton("WyjdŸ", delegate
                            {
                                GameManager.thLock = false;
                                Finish();
                            });
                            ad.Show();
                        });
                        return;

                        break;

                    case MessageTypes.LeftClient:
                        RunOnUiThread(delegate
                        {
                            ad = new AlertDialog.Builder(this).Create();
                            ad.SetCancelable(false);     // This blocks the 'BACK' button
                            ad.SetMessage("Twój przeciwnik opuœci³ grê!");
                            ad.SetButton("WyjdŸ", delegate
                            {
                                //th.Abort();
                                GameManager.thLock = false;
                                Finish();
                            });
                            ad.Show();
                        });
                        return;

                        break;
                    }
                }
                catch (System.Threading.ThreadAbortException e)
                {
                    return;
                }
                catch (Exception e)
                {
                    Sockets.client.Close();
                    RunOnUiThread(delegate
                    {
                        ad = new AlertDialog.Builder(this).Create();
                        ad.SetCancelable(false); // This blocks the 'BACK' button
                        ad.SetMessage("Nie mo¿na po³¹czyæ siê z serwerem. SprawdŸ po³¹czenie z internetem.");
                        ad.SetButton("OK", delegate
                        {
                            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                        });
                        ad.Show();
                    });
                }
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewTeam);
            ActionBar.Title = "Your Team";
            ActionBar.SetHomeButtonEnabled(true);
            ActionBar.SetDisplayHomeAsUpEnabled(true);

            // Set Widgets:
            overrideTeam = FindViewById <Button>(Resource.Id.btnOverrideCurrentTeam);
            teamPlayers  = FindViewById <ListView>(Resource.Id.lvTeamPlayers);

            // Configure ListView:

            // Push formatted team data to list view:
            teamData = services.GetTeamData();

            for (int i = 0; i < teamData.Count; i++)
            {
                Player currentInLoop = teamData[i];

                string line1 = "Name: " + currentInLoop.FirstName + " " + currentInLoop.LastName;
                string line2 = "Number: " + currentInLoop.PlayerNumber;
                string line3 = "Position: " + currentInLoop.PlayerPosition;

                string displayMe = line1 + "\n\n" + line2 + "\n\n" + line3;

                formattedTeamData.Add(displayMe);
            }

            teamDataAdapter     = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, formattedTeamData);
            teamPlayers.Adapter = teamDataAdapter;

            // Handle Clicks:

            // Create New Team Button:
            overrideTeam.Click += delegate
            {
                // Check if the user really wants to override their current team configuration:
                AlertDialog.Builder confirm = new AlertDialog.Builder(this);
                confirm.SetTitle("Confirm");

                string line1 = "Creating a new team will delete your current team.";
                string line2 = "Remove current team and make a new one?";

                string message = line1 + "\n\n" + line2;
                confirm.SetMessage(message);

                confirm.SetPositiveButton("Yes", delegate
                {
                    Intent newActivity = new Intent(this, typeof(CreateNewTeam));
                    StartActivity(newActivity);

                    confirm.Dispose();
                });

                confirm.SetNegativeButton("No", delegate
                {
                    confirm.Dispose();
                });

                confirm.Show();
            };
        }
        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);
        }
        private async void SaveMapAsync(object sender, OnSaveMapEventArgs e)
        {
            var alertBuilder = new AlertDialog.Builder(this);

            // Get the current map
            var myMap = _myMapView.Map;

            try
            {
                // Show the progress bar so the user knows work is happening
                _progressBar.Visibility = ViewStates.Visible;

                // Get information entered by the user for the new portal item properties
                var title       = e.MapTitle;
                var description = e.MapDescription;
                var tags        = e.Tags;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Export the current map view for the item's thumbnail
                RuntimeImage thumbnailImg = await _myMapView.ExportImageAsync();

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Call a function to save the map as a new portal item
                    await SaveNewMapAsync(myMap, title, description, tags, thumbnailImg);

                    // Report a successful save
                    alertBuilder.SetTitle("Map Saved");
                    alertBuilder.SetMessage("Saved '" + title + "' to ArcGIS Online!");
                    alertBuilder.Show();
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Get the file stream from the new thumbnail image
                    Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();

                    // Update the item thumbnail
                    (myMap.Item as PortalItem).SetThumbnailWithImage(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful
                    alertBuilder.SetTitle("Updates Saved");
                    alertBuilder.SetMessage("Saved changes to '" + myMap.Item.Title + "'");
                    alertBuilder.Show();
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                alertBuilder.SetTitle("Unable to save map");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }
            finally
            {
                // Hide the progress bar
                _progressBar.Visibility = ViewStates.Invisible;
            }
        }
Exemple #18
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.menusincronizacion);
            /////////////////////////////Mappings//////////////////////////
            botonabrirqr    = FindViewById <ImageView>(Resource.Id.imageView1);
            nombreservidor  = FindViewById <TextView>(Resource.Id.textView2);
            playpause       = FindViewById <ImageView>(Resource.Id.imageView3);
            homeb           = FindViewById <ImageView>(Resource.Id.imageView2);
            ll              = FindViewById <LinearLayout>(Resource.Id.linearLayout1);
            tvnombrecancion = FindViewById <TextView>(Resource.Id.textView3);
            root            = FindViewById <LinearLayout>(Resource.Id.rooteeooo);
            ////////////////////////////////////////////////////////////////
            ll.SetBackgroundColor(Android.Graphics.Color.Black);
            //   root.SetBackgroundColor(Android.Graphics.Color.DarkGray);
            cliente      = new TcpClient();
            cliente2     = new TcpClient();
            clientelocal = new TcpClient();
            clientelocal.Client.Connect(Intent.GetStringExtra("ipadre"), 1024);
            //    ll.SetBackgroundColor(Android.Graphics.Color.Black);
            // animar2(ll);
            UiHelper.SetBackgroundAndRefresh(this);
            //    ll.SetBackgroundColor(Android.Graphics.Color.ParseColor("#2b2e30"));
            servidor = new TcpListener(IPAddress.Any, 1060);
            botonabrirqr.SetBackgroundResource(Resource.Drawable.synchalf);
            vero = new Thread(new ThreadStart(cojerstreamlocal));
            vero.IsBackground = true;
            vero.Start();
            tvnombrecancion.Selected = true;
            homeb.Click += delegate
            {
                this.Finish();
            };
            playpause.Click += delegate
            {
                animar(playpause);
                clientelocal.Client.Send(Encoding.UTF8.GetBytes("playpause()"));
            };
            botonabrirqr.Click += async(ss, sss) =>
            {
                if (conectado == false)
                {
                    animar(botonabrirqr);
                    ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
                    var scanner = new ZXing.Mobile.MobileBarcodeScanner();

                    var resultado = await scanner.Scan();

                    string captured = resultado.Text.Trim();
                    ipadres = captured.Split(';')[0];
                    puerto  = int.Parse(captured.Split(';')[1]);
                    cliente.Client.Connect(ipadres, puerto);
                    // botonabrirqr.Visibility = ViewStates.Invisible;

                    Toast.MakeText(this, "conectado..", ToastLength.Long).Show();

                    conocerset = new Thread(new ThreadStart(conocerse));
                    conocerset.IsBackground = true;
                    conocerset.Start();
                    cojert = new Thread(new ThreadStart(cojerstream));
                    cojert.IsBackground = true;
                    cojert.Start();
                    conectado = true;
                }
                else
                {
                    AlertDialog.Builder ad = new AlertDialog.Builder(this);
                    ad.SetCancelable(false);
                    ad.SetMessage("Desea desconectarse??");
                    ad.SetTitle("Advertencia");
                    ad.SetIcon(Resource.Drawable.warningsignonatriangularbackground);
                    ad.SetPositiveButton("Si", alertaok);
                    ad.SetNegativeButton("No", alertano);
                    ad.Create();
                    ad.Show();
                }
            };
        }
Exemple #19
0
        private void getempxml(object sender, ProjectListCompletedEventArgs e)
        {
            try{
                DataSet ds       = new DataSet();
                string  innerxml = e.Result.InnerXml.ToString();
                innerxml = "<ds>" + innerxml + "</ds>";
                DataTable dataTable = new DataTable("Project");
                dataTable.Columns.Add("ProjectID", typeof(string));
                dataTable.Columns.Add("Projectname", typeof(string));
                dataTable.Columns.Add("clientname", typeof(string));
                dataTable.Columns.Add("addeddate", typeof(string));
                ds.Tables.Add(dataTable);
                System.IO.StringReader xmlSR = new System.IO.StringReader(innerxml);
                ds.ReadXml(xmlSR, XmlReadMode.IgnoreSchema);
                dataTable         = ds.Tables [0];
                tableItems        = new List <TableItem> ();
                filterdtableItems = new List <TableItem> ();

                if (dataTable.Rows.Count > 0)
                {
                    if (UserType == 1)
                    {
                        if (dataTable.Rows.Count == 1)
                        {
                            foreach (DataRow dr in dataTable.Rows)
                            {
                                if (dr ["ProjectID"].ToString() != "0")
                                {
                                    //_fab.Visibility=ViewStates.Gone;
                                }
                                else
                                {
                                    _fab.Visibility = ViewStates.Visible;
                                }
                            }
                        }
                        else
                        {
                            _fab.Visibility = ViewStates.Gone;
                        }
                    }

                    foreach (DataRow dr in dataTable.Rows)
                    {
                        if (dr ["ProjectID"].ToString() != "0")
                        {
                            string   date          = dr ["addeddate"].ToString();
                            DateTime dt            = DateTime.Parse(date, CultureInfo.GetCultureInfo("en-gb"));
                            string   converteddate = Convert.ToDateTime(dt).ToString("MM-dd-yyyy HH:mm:ss");
                            tableItems.Add(new TableItem()
                            {
                                Projectname = dr ["Projectname"].ToString(),
                                addeddate   = converteddate,
                                ClientName  = dr ["clientname"].ToString(),
                                ProjectID   = dr ["ProjectID"].ToString()
                            });
                        }
                        else
                        {
                            freeproject = 1;
                            tableItems.Add(new TableItem()
                            {
                                Projectname = "No project found",
                                addeddate   = "",
                                ClientName  = "",
                                ProjectID   = ""
                            });
                        }
                    }
                }
                else
                {
                    freeproject = 1;

                    tableItems.Add(new TableItem()
                    {
                        Projectname = "No project found",
                        addeddate   = "",
                        ClientName  = "",
                        ProjectID   = ""
                    });
                }
                filterdtableItems = tableItems;
                //listView = FindViewById<ListView>(Resource.Id.List); // get reference to the ListView in the layout
                // populate the listview with data
                listView.Adapter = new ProjectScreenAdapter(this, tableItems);

                projectloadingdialog.Dismiss();
            }
            catch (Exception ex) {
                projectloadingdialog.Dismiss();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetCancelable(false);
                builder.SetMessage("Please check your device internet. And try again");
                builder.SetNeutralButton("Ok", (object buldersender, DialogClickEventArgs clickevent) => {
                    projectloadingdialog.Dismiss();
                    StartActivity(typeof(Main));
                });
                AlertDialog alertdialog = builder.Create();
                alertdialog.Show();
            }
            //listView.ItemClick += OnListItemClick;
            //listView.SetFooterDividersEnabled(false);
        }
Exemple #20
0
        private void Initialize()
        {
            try
            {
                // Define the Uri for the service feature table (US state polygons)
                Uri myServiceFeatureTable_Uri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

                // Create a new service feature table from the Uri
                ServiceFeatureTable myServiceFeatureTable = new ServiceFeatureTable(myServiceFeatureTable_Uri);

                // Create a new feature layer from the service feature table
                FeatureLayer myFeatureLayer = new FeatureLayer(myServiceFeatureTable)
                {
                    // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work)
                    RenderingMode = FeatureRenderingMode.Dynamic
                };

                // Create a new simple line symbol for the feature layer
                SimpleLineSymbol mySimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1);

                // Create a new simple fill symbol for the feature layer
                SimpleFillSymbol mysimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, mySimpleLineSymbol);

                // Create a new simple renderer for the feature layer
                SimpleRenderer mySimpleRenderer = new SimpleRenderer(mysimpleFillSymbol);

                // Get the scene properties from the simple renderer
                RendererSceneProperties myRendererSceneProperties = mySimpleRenderer.SceneProperties;

                // Set the extrusion mode for the scene properties
                myRendererSceneProperties.ExtrusionMode = ExtrusionMode.AbsoluteHeight;

                // Set the initial extrusion expression
                myRendererSceneProperties.ExtrusionExpression = "[POP2007] / 10";

                // Set the feature layer's renderer to the define simple renderer
                myFeatureLayer.Renderer = mySimpleRenderer;

                // Create a new scene with the topographic backdrop
                Scene myScene = new Scene(BasemapType.Topographic);

                // Set the scene view's scene to the newly create one
                _mySceneView.Scene = myScene;

                // Add the feature layer to the scene's operational layer collection
                myScene.OperationalLayers.Add(myFeatureLayer);

                // Create a new map point to define where to look on the scene view
                MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator);

                // Create a new orbit location camera controller using the map point and defined distance
                OrbitLocationCameraController myOrbitLocationCameraController = new OrbitLocationCameraController(myMapPoint, 20000000);

                // Set the scene view's camera controller to the orbit location camera controller
                _mySceneView.CameraController = myOrbitLocationCameraController;
            }
            catch (Exception ex)
            {
                // Something went wrong, display the error
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Error");
                alert.SetMessage(ex.Message);
                alert.Show();
            }
        }
Exemple #21
0
 public static void MostrarMensaje(Activity _actividad, string Mensaje)
 {
     AlertDialog.Builder d = new AlertDialog.Builder(_actividad);
     d.SetMessage(Mensaje);
     d.Show();
 }
Exemple #22
0
        protected override void OnCreate(Bundle bundle)
        {
            Stopwatch st = new Stopwatch();

            st.Start();
            base.OnCreate(bundle);
            uid = Convert.ToInt32(CurrentUser.getUserId());
            try
            {
                ActionBar.SetHomeButtonEnabled(true);
                ActionBar.SetDisplayHomeAsUpEnabled(true);
                ServiceWrapper     svc        = new ServiceWrapper();
                ItemReviewResponse uidreviews = new ItemReviewResponse();
                uidreviews = svc.GetItemReviewUID(uid).Result;
                List <Review> myArr1;
                myArr1 = uidreviews.Reviews.ToList();
                int c = uidreviews.Reviews.Count;
                if (c == 0)
                {
                    var data = svc.GetMyTastingsList(uid).Result;


                    SetContentView(Resource.Layout.ReviewEmpty);
                    txtName = FindViewById <TextView>(Resource.Id.textView1);
                    if (data.TastingList.Count != 0)
                    {
                        txtName.Text = "You have tasted " + data.TastingList.Count + " wines.\n We would love to hear your feedback.";
                    }
                    else
                    {
                        txtName.Text = "Please taste and then review.";
                    }
                    Imag = FindViewById <ImageView>(Resource.Id.imageView1);
                    var TaskA = new System.Threading.Tasks.Task(() =>
                    {
                        Imag.SetImageResource(Resource.Drawable.ReviewIns);
                    });
                    TaskA.Start();
                }
                else
                {
                    SetContentView(Resource.Layout.MyReviews);
                    var             wineList  = FindViewById <ListView>(Resource.Id.listView1);
                    Review          edit      = new Review();
                    ReviewPopup     editPopup = new ReviewPopup(this, edit);
                    MyReviewAdapter adapter   = new MyReviewAdapter(this, myArr1);
                    wineList.Adapter = adapter;

                    wineList.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args)
                    {
                        string WineBarcode = myArr1[args.Position].Barcode;
                        int    storeID     = Convert.ToInt32(myArr1[args.Position].PlantFinal);
                        LoggingClass.LogInfoEx("Clicked on " + myArr1[args.Position].Barcode + " to enter into wine details From ReviewAct", screenid);
                        ProgressIndicator.Show(this);
                        //AndHUD.Shared.Show(this, "Loading...", Convert.ToInt32(MaskType.Clear));
                        var intent = new Intent(this, typeof(DetailViewActivity));
                        intent.PutExtra("WineBarcode", WineBarcode);
                        intent.PutExtra("storeid", storeID);
                        StartActivity(intent);
                    };

                    LoggingClass.LogInfo("Entered into My Review", screenid);
                }
                ProgressIndicator.Hide();
            }
            catch (Exception exe)
            {
                LoggingClass.LogError(exe.Message, screenid, exe.StackTrace.ToString());
                AndHUD.Shared.Dismiss();
                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();
            }
            st.Stop();
            LoggingClass.LogTime("Reviewactivity", st.Elapsed.TotalSeconds.ToString());
        }
        public override async Task <JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
        {
            MobileServicePreconditionFailedException error;

            do
            {
                error = null;

                try
                {
                    return(await operation.ExecuteAsync());
                }
                catch (MobileServicePreconditionFailedException ex)
                {
                    error = ex;
                }

                if (error != null)
                {
                    var localItem   = operation.Item.ToObject <ToDoItem>();
                    var serverValue = error.Value;

                    var builder = new AlertDialog.Builder(this.activity);
                    builder.SetTitle("Conflict between local and server versions");
                    builder.SetMessage("How do you want to resolve this conflict?\n\n" + "Local item: \n" + localItem +
                                       "\n\nServer item:\n" + serverValue.ToObject <ToDoItem>());

                    var clickTask = new TaskCompletionSource <int>();

                    builder.SetPositiveButton(LOCAL_VERSION, (which, e) =>
                    {
                        clickTask.SetResult(1);
                    });
                    builder.SetNegativeButton(SERVER_VERSION, (which, e) =>
                    {
                        clickTask.SetResult(2);
                    });
                    builder.SetOnCancelListener(new CancelListener(clickTask));

                    builder.Create().Show();

                    int command = await clickTask.Task;
                    if (command == 1)
                    {
                        // Overwrite the server version and try the operation again by continuing the loop
                        operation.Item[MobileServiceSystemColumns.Version] = serverValue[MobileServiceSystemColumns.Version];
                        continue;
                    }
                    else if (command == 2)
                    {
                        return((JObject)serverValue);
                    }
                    else
                    {
                        operation.AbortPush();
                    }
                }
            } while (error != null);

            return(null);
        }
Exemple #24
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            EditText phoneNumberText   = FindViewById <EditText>(Resource.Id.PhoneNumberText);
            Button   translateButton   = FindViewById <Button>(Resource.Id.TranslateButton);
            Button   callButton        = FindViewById <Button>(Resource.Id.CallButton);
            Button   callHistoryButton = FindViewById <Button>(Resource.Id.CallHistoryButton);

            // "Call" を Disable にします
            callButton.Enabled = false;
            // 番号を変換するコードを追加します。
            string translatedNumber = string.Empty;

            translateButton.Click += (object sender, EventArgs e) =>
            {
                // ユーザーのアルファベットの電話番号を電話番号に変換します。
                translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
                if (String.IsNullOrWhiteSpace(translatedNumber))
                {
                    callButton.Text    = "Call";
                    callButton.Enabled = false;
                }
                else
                {
                    callButton.Text    = "Call " + translatedNumber;
                    callButton.Enabled = true;
                }
            };

            callButton.Click += (object sender, EventArgs e) =>
            {
                // "Call" ボタンがクリックされたら電話番号へのダイヤルを試みます。
                var callDialog = new AlertDialog.Builder(this);
                callDialog.SetMessage("Call " + translatedNumber + "?");
                callDialog.SetNeutralButton("Call", delegate
                {
                    // 掛けた番号のリストに番号を追加します。
                    phoneNumbers.Add(translatedNumber);
                    // Call History ボタンを有効にします。
                    callHistoryButton.Enabled = true;
                    // 電話への intent を作成します。
                    var callIntent = new Intent(Intent.ActionCall);
                    callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
                    StartActivity(callIntent);
                });
                callDialog.SetNegativeButton("Cancel", delegate { });
                // アラートダイアログを表示し、ユーザーのレスポンスを待ちます。
                callDialog.Show();
            };

            callHistoryButton.Click += (sender, e) =>
            {
                var intent = new Intent(this, typeof(CallHistoryActivity));
                intent.PutStringArrayListExtra("phone_numbers", phoneNumbers);
                StartActivity(intent);
            };
        }
Exemple #25
0
        private async void ReadMobileStyle(string mobileStyleFilePath)
        {
            try
            {
                // Make sure the file exists.
                if (!System.IO.File.Exists(mobileStyleFilePath))
                {
                    throw new System.IO.FileNotFoundException("Mobile style file not found at " + mobileStyleFilePath);
                }

                // Open the mobile style file at the path provided.
                _emojiStyle = await SymbolStyle.OpenAsync(mobileStyleFilePath);

                // Get the default style search parameters.
                SymbolStyleSearchParameters searchParams = await _emojiStyle.GetDefaultSearchParametersAsync();

                // Search the style with the default parameters to return a list of all symbol results.
                IList <SymbolStyleSearchResult> styleResults = await _emojiStyle.SearchSymbolsAsync(searchParams);

                // Loop through the results and put symbols into the appropriate list according to category (eyes, mouth, hat).
                foreach (SymbolStyleSearchResult result in styleResults)
                {
                    // Get the result symbol as a multilayer point symbol.
                    MultilayerPointSymbol multiLayerSym = result.Symbol as MultilayerPointSymbol;

                    // Create a swatch for the symbol and use it to create a bitmap image.
                    RuntimeImage swatch = await multiLayerSym.CreateSwatchAsync();

                    Bitmap symbolImage = await swatch.ToImageSourceAsync();

                    // Check the symbol category.
                    switch (result.Category)
                    {
                    // Add a new SymbolLayerInfo to represent the symbol and add it to its category list.
                    // SymbolLayerInfo is a custom class with properties for the symbol name, swatch image, and unique key.
                    case "Eyes":
                    {
                        _eyeSymbolInfos.Add(new SymbolLayerInfo(result.Name, symbolImage, result.Key));
                        break;
                    }

                    case "Mouth":
                    {
                        _mouthSymbolInfos.Add(new SymbolLayerInfo(result.Name, symbolImage, result.Key));
                        break;
                    }

                    case "Hat":
                    {
                        _hatSymbolInfos.Add(new SymbolLayerInfo(result.Name, symbolImage, result.Key));
                        break;
                    }

                    case "Face":
                    {
                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                // Show the exception message.
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Activity);
                alertBuilder.SetTitle("Error reading style");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }
        }
Exemple #26
0
        private void BtnSend_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    foreach (var i in AssignJobP3Activity.WorkerList)
                    {
                        var parts = SmsManager.Default.DivideMessage(txtMsg.Text);
                        SmsManager.Default.SendMultipartTextMessage(i.empMobile, null, parts, null, null);
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "A message failed to send\n" + ex, ToastLength.Long).Show();
                }

                Toast.MakeText(this, "Messages sent", ToastLength.Long).Show();
                btnSend.Enabled = false;

                JobInstructions = txtMsg.Text.Split(new string[] { "Note:" }, StringSplitOptions.None).Last();          //NEEDSTEST
                JobsAssigned job = new JobsAssigned();
                foreach (var worker in AssignJobP3Activity.WorkerList)
                {
                    EmployeeJob emp1 = new EmployeeJob();
                    emp1.EmpNAME = worker.empNAME;
                    job.EmployeeJobs.Add(emp1);
                }

                startTime = JobDate + "T" + JobTime;

                job.AssignJOBNUM       = JobNumber.ToString();
                job.AssignCLIENT       = JobClient;
                job.AssignWORK         = JobName;
                job.AssignAREA         = JobArea;
                job.AssignINSTRUCTIONS = JobInstructions;
                job.AssignTRUCK        = JobTruckNo;
                job.TextSENT           = DateTime.Now.ToString("yyyy-MM-dd" + "T" + "HH:mm:ss");
                job.AssignSTARTTIME    = startTime;


                try
                {
                    objJOBS.ExecutePostRequest(job);
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, "Something went wrong:" + ex.Message, ToastLength.Long).Show();
                }

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

                alertDialog.SetMessage("Message sent and saved.");
                alertDialog.SetPositiveButton("New Message", delegate
                {
                    StartActivity(typeof(AssignJobP2Activity));
                    alertDialog.Dispose();
                });
                alertDialog.SetNegativeButton("Menu", delegate
                {
                    StartActivity(typeof(MainActivity));
                    alertDialog.Dispose();
                });
                alertDialog.Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Something went wrong:" + ex.Message, ToastLength.Long).Show();
            }
        }
Exemple #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get the UI controls from the loaded layout:
            EditText phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText);
            Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);
            Button callButton = FindViewById<Button>(Resource.Id.CallButton);

            // Disable the "Call" button
            callButton.Enabled = false;

            // Add code to translate number
            string translatedNumber = string.Empty;

            translateButton.Click += (object sender, EventArgs e) =>
            {
                // Translate user's alphanumeric phone number to numeric
                translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
                if (String.IsNullOrWhiteSpace(translatedNumber))
                {
                    callButton.Text = "Call";
                    callButton.Enabled = false;
                }
                else
                {
                    callButton.Text = "Call " + translatedNumber;
                    callButton.Enabled = true;
                }
            };

            Button callHistoryButton = FindViewById<Button>(Resource.Id.CallHistoryButton);

            callHistoryButton.Click += (sender, e) =>
            {
                var intent = new Intent(this, typeof(CallHistoryActivity));
                intent.PutStringArrayListExtra("phone_numbers", phoneNumbers);
                StartActivity(intent);
            };

            callButton.Click += (object sender, EventArgs e) =>
            {
                // On "Call" button click, try to dial phone number.
                var callDialog = new AlertDialog.Builder(this);
                callDialog.SetMessage("Call " + translatedNumber + "?");
                callDialog.SetNeutralButton("Call", delegate
                {
                    // add dialed number to list of called numbers.
                    phoneNumbers.Add(translatedNumber);
                    // enable the Call History button
                    callHistoryButton.Enabled = true;
                    // Create intent to dial phone
                    var callIntent = new Intent(Intent.ActionDial);
                    callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
                    StartActivity(callIntent);
                });
                callDialog.SetNegativeButton("Cancel", delegate { });

                // Show the alert dialog to the user and wait for response.
                callDialog.Show();
            };
        }
		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
			};
		}
        protected override void OnCreate(Bundle savedInstanceState)
        {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.SetVmPolicy(builder.Build());

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Main);

            if (IsThereAnAppToTakePictures())
            {
                CreateDirectoryForPictures();
                Button button = FindViewById <Button>(Resource.Id.myButton);
                _imageView    = FindViewById <ImageView>(Resource.Id.imageView1);
                button.Click += TakeAPicture;
            }

            Normal   = FindViewById <RadioButton>(Resource.Id.radioButton1);
            Follow   = FindViewById <RadioButton>(Resource.Id.radioButton2);
            textview = FindViewById <TextView>(Resource.Id.textView1);

            Normal.Click += RadioButtonClick;
            Follow.Click += RadioButtonClick;


            SetUpMap();

            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation }, 1);

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Permission.Granted)
            {
                locationManager = (LocationManager)GetSystemService(Context.LocationService);
                provider        = locationManager.GetBestProvider(new Criteria(), false);
                Location location = locationManager.GetLastKnownLocation(provider);

                if (location != null)
                {
                    lat = location.Latitude;    //location.Latitude;
                    lon = location.Longitude;   //location.Longitude;
                }
                else
                {
                    lat = 51.9204144;   //location.Latitude;
                    lon = 4.4840513;    //location.Longitude;

                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                    alertDialog.SetTitle("WARNING");
                    alertDialog.SetMessage("Cant find a location");
                    alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); });

                    alertDialog.Show();
                }

                Thread timerThread = new Thread(new ThreadStart(this.TimerThread));
                timerThread.Start();
            }
            else
            {
                System.Console.WriteLine("dikke moeder");
            }
        }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.devicelistview, parent, false);



            var deviceName  = view.FindViewById <TextView>(Resource.Id.tvdevicename);
            var deviceOn    = view.FindViewById <Button>(Resource.Id.btndeviceon);
            var deviceOff   = view.FindViewById <Button>(Resource.Id.btndeviceoff);
            var deviceTimer = view.FindViewById <Button>(Resource.Id.btndevicetimer);


            //GetDevices GD = new GetDevices();
            //List<devicesItem> deviceslist = new List<devicesItem>();

            //deviceslist = await GD.GetDeviceList();

            //deviceName.Text = "DeviceName";
            deviceName.Text  = devicelistArrayList[position].deviceName + " " + devicelistArrayList[position].deviceId;
            deviceOn.Text    = devicelistArrayList[position].deviceOn;
            deviceOff.Text   = devicelistArrayList[position].deviceOff;
            deviceTimer.Text = devicelistArrayList[position].timer.ToString();


            var localOn    = new LocalOnclickListener();
            var localOff   = new LocalOnclickListener();
            var localTimer = new LocalOnclickListener();


            localOn.HandleOnClick = () =>
            {
                HttpWebRequestHandler HWRH = new HttpWebRequestHandler(activity);
                int id = position + 1;
                //Toast.MakeText(this.activity, devicelistArrayList[position].Name + "DEVICEON id: " + position, ToastLength.Short).Show();
                HWRH.webRestHandler(id.ToString(), null, "on", devicelistArrayList[position].timer.ToString(), "control");
                Log.Info("ButtonOn: ", "Clicked");
            };



            localOff.HandleOnClick = () =>
            {
                HttpWebRequestHandler HWRH = new HttpWebRequestHandler(activity);
                int id = position + 1;
                //Toast.MakeText(this.activity, devicelistArrayList[position].Name + "DEVICEON id: " + position, ToastLength.Short).Show();
                HWRH.webRestHandler(id.ToString(), null, "off", "0", "control");
                Log.Info("ButtonOFF: ", "Clicked");
            };

            localTimer.HandleOnClick = () =>
            {
                //Toast.MakeText(this.activity, devicelistArrayList[position].Name + "DEVICETIMER id: " + position, ToastLength.Short).Show();
            };

            deviceOn.SetOnClickListener(localOn);
            deviceOff.SetOnClickListener(localOff);
            deviceTimer.SetOnClickListener(localTimer);
            deviceName.LongClick += delegate
            {
                AlertDialog.Builder alert = new AlertDialog.Builder(activity);
                alert.SetTitle("Remove device?");
                alert.SetMessage("Press OK if you really want delete device");
                alert.SetPositiveButton("OK", (senderAlert, args) =>
                {
                    HttpWebRequestHandler HWRH = new HttpWebRequestHandler(activity);
                    int id = position + 1;
                    HWRH.webRestHandler(id.ToString(), null, null, null, "delete");
                    Toast.MakeText(activity, "DELETING DEVICE... " + id.ToString(), ToastLength.Long).Show();
                    devicelistArrayList.RemoveAt(position);
                    //Recreate activity for refreshing listview
                    activity.Recreate();
                });

                alert.SetNegativeButton("Cancel", (senderAlert, args) =>
                {
                });

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



            //deviceOn.Click += delegate
            //{
            //    int deviceId = devicelistArrayList[position].id;
            //    string deviceName = devicelistArrayList[position].Name;

            //    //Toast.MakeText(this.activity,"DeviceOn id: "+ deviceId, ToastLength.Short).Show();

            //    if (deviceName == "kahvinkeitin " + deviceId)
            //    {
            //        Toast.MakeText(this.activity, "IF DeviceOn id: " + deviceId, ToastLength.Short).Show();
            //    }

            //};

            return(view);
        }
        private void SamplePageContents(Android.Content.Context con)
        {
            //Title list
            Title.Add("Software");
            Title.Add("Banking");
            Title.Add("Media");
            Title.Add("Medical");

            //jobSearchLabel
            jobSearchLabel          = new TextView(con);
            jobSearchLabel.Text     = "Job Search";
            jobSearchLabel.TextSize = 30;
            jobSearchLabel.Typeface = Typeface.DefaultBold;

            //jobSearchLabelSpacing
            jobSearchLabelSpacing = new TextView(con);
            jobSearchLabelSpacing.SetHeight(40);

            //countryLabel
            countryLabel          = new TextView(con);
            countryLabel.Text     = "Country";
            countryLabel.TextSize = 16;

            //countryLabelSpacing
            countryLabelSpacing = new TextView(con);
            countryLabelSpacing.SetHeight(10);

            //countryAutoCompleteSpacing
            countryAutoCompleteSpacing = new TextView(con);
            countryAutoCompleteSpacing.SetHeight(30);

            //jobFieldLabel
            jobFieldLabel          = new TextView(con);
            jobFieldLabel.Text     = "Job Field";
            jobFieldLabel.TextSize = 16;

            //jobFieldLabelSpacing
            jobFieldLabelSpacing = new TextView(con);
            jobFieldLabelSpacing.SetHeight(10);

            //jobFieldAutoCompleteSpacing
            jobFieldAutoCompleteSpacing = new TextView(con);
            jobFieldAutoCompleteSpacing.SetHeight(30);

            //experienceLabel
            experienceLabel          = new TextView(con);
            experienceLabel.Text     = "Experience";
            experienceLabel.TextSize = 16;

            //experienceLabelSpacing
            experienceLabelSpacing = new TextView(con);
            experienceLabelSpacing.SetHeight(10);

            //Experience list
            Experience.Add("1");
            Experience.Add("2");

            //searchButton
            searchButton = new Button(con);
            searchButton.SetWidth(ActionBar.LayoutParams.MatchParent);
            searchButton.SetHeight(40);
            searchButton.Text = "Search";
            searchButton.SetTextColor(Color.White);
            searchButton.SetBackgroundColor(Color.Gray);
            searchButton.Click += (object sender, EventArgs e) => {
                GetResult();
                resultsDialog.SetMessage(jobNumber + " Jobs Found");
                resultsDialog.Create().Show();
            };

            //searchButtonSpacing
            searchButtonSpacing = new TextView(con);
            searchButtonSpacing.SetHeight(30);

            //experience Spinner
            experienceSpinner = new Spinner(con, SpinnerMode.Dialog);
            experienceSpinner.DropDownWidth = 500;
            experienceSpinner.SetBackgroundColor(Color.Gray);
            ArrayAdapter <String> experienceDataAdapter = new ArrayAdapter <String>
                                                              (con, Android.Resource.Layout.SimpleSpinnerItem, Experience);

            experienceDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            experienceSpinner.Adapter = experienceDataAdapter;

            //experienceSpinnerSpacing
            experienceSpinnerSpacing = new TextView(con);
            experienceSpinnerSpacing.SetHeight(30);

            //results dialog
            resultsDialog = new AlertDialog.Builder(con);
            resultsDialog.SetTitle("Results");
            resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) =>
            {
            });
            resultsDialog.SetCancelable(true);
        }
 public void OtpVerification(string sentOtp, string receivedOtp, string username)
 {
     //starting of otp verification code
     if (sentOtp == receivedOtp)
     {
         AlertDialog.Builder alert = new AlertDialog.Builder(this);
         alert.SetTitle("Successfully your logged in");
         alert.SetMessage("Thank You");
         alert.SetNegativeButton("Ok", delegate { });
         Dialog dialog = alert.Create();
         dialog.Show();
         CustomerResponse authen = new CustomerResponse();
         ServiceWrapper   svc    = new ServiceWrapper();
         try
         {
             /// authen = svc.AuthencateUser(username).Result;
             if (authen.customer != null && authen.customer.CustomerID != 0)
             {
                 CurrentUser.SaveUserName(username, authen.customer.CustomerID.ToString());
                 Intent intent = new Intent(this, typeof(TabActivity));
                 StartActivity(intent);
             }
             else
             {
                 AlertDialog.Builder aler = new AlertDialog.Builder(this);
                 aler.SetTitle("Sorry");
                 aler.SetMessage("You entered wrong ");
                 aler.SetNegativeButton("Ok", delegate { });
                 Dialog dialog1 = aler.Create();
                 dialog1.Show();
             };
         }
         catch (Exception exception)
         {
             if (exception.Message.ToString() == "One or more errors occurred.")
             {
                 AlertDialog.Builder aler = new AlertDialog.Builder(this);
                 aler.SetTitle("Sorry");
                 aler.SetMessage("Please check your internet connection");
                 aler.SetNegativeButton("Ok", delegate { });
                 Dialog dialog2 = aler.Create();
                 dialog2.Show();
             }
             else
             {
                 AlertDialog.Builder aler = new AlertDialog.Builder(this);
                 aler.SetTitle("Sorry");
                 aler.SetMessage("We're under maintanence");
                 aler.SetNegativeButton("Ok", delegate { });
                 Dialog dialog3 = aler.Create();
                 dialog3.Show();
             }
         }
     }
     else
     {
         AlertDialog.Builder aler = new AlertDialog.Builder(this);
         aler.SetTitle("Incorrect Otp");
         aler.SetMessage("Please Check Again");
         aler.SetNegativeButton("Ok", delegate { });
         Dialog dialog = aler.Create();
         dialog.Show();
     }
     //Ending of otp verification code
 }
Exemple #33
0
        private async Task CalculateViewshed(MapPoint location)
        {
            // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a
            // user click on the map and then display the results back as a polygon fill graphics overlay. If there
            // is a problem with the execution of the geoprocessing task an error message will be displayed

            // Create new geoprocessing task using the url defined in the member variables section
            GeoprocessingTask myViewshedTask = await GeoprocessingTask.CreateAsync(new Uri(_viewshedUrl));

            // Create a new feature collection table based upon point geometries using the current map view spatial reference
            FeatureCollectionTable myInputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, _myMapView.SpatialReference);

            // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet
            Feature myInputFeature = myInputFeatures.CreateFeature();

            // Assign a physical location to the new point feature based upon where the user clicked in the map view
            myInputFeature.Geometry = location;

            // Add the new feature with (x,y) location to the feature collection table
            await myInputFeatures.AddFeatureAsync(myInputFeature);

            // Create the parameters that are passed to the used geoprocessing task
            GeoprocessingParameters myViewshedParameters =
                new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute)
            {
                // Request the output features to use the same SpatialReference as the map view
                OutputSpatialReference = _myMapView.SpatialReference
            };

            // Add an input location to the geoprocessing parameters
            myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures));

            // Create the job that handles the communication between the application and the geoprocessing task
            GeoprocessingJob myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters);

            try
            {
                // Execute analysis and wait for the results
                GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync();

                // Get the results from the outputs
                GeoprocessingFeatures myViewshedResultFeatures = (GeoprocessingFeatures)myAnalysisResult.Outputs["Viewshed_Result"];

                // Add all the results as a graphics to the map
                IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features;
                foreach (Feature myFeature in myViewshedAreas)
                {
                    _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry));
                }
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem
                if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null)
                {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                    alertBuilder.SetTitle("Geoprocessing error");
                    alertBuilder.SetMessage("Executing geoprocessing failed. " + myViewshedJob.Error.Message);
                    alertBuilder.Show();
                }
                else
                {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                    alertBuilder.SetTitle("Sample error");
                    alertBuilder.SetMessage("An error occurred. " + ex);
                    alertBuilder.Show();
                }
            }
            finally
            {
                // Indicate that the geoprocessing is not running
                SetBusy(false);
            }
        }
Exemple #34
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( );
         } );
 }