Пример #1
0
        public Task <bool> DisplaySettingsAlert(string title, string message, string cancel = "Cancel")
        {
            var taskCompletionSource = new TaskCompletionSource <bool>();

            var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

            SetAttributedText(alert, title, message);

            UIAlertAction cancelAction = UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, action => taskCompletionSource.SetResult(false));

            alert.AddAction(cancelAction);

            // Provide quick access to Settings.
            UIAlertAction settingsAction = UIAlertAction.Create("Settings", UIAlertActionStyle.Default, action =>
            {
                UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
                taskCompletionSource.SetResult(true);
            });

            alert.AddAction(settingsAction);
            NavigationHelper.GetActiveViewController().PresentViewController(alert, true, null);

            return(taskCompletionSource.Task);
        }
Пример #2
0
        public Task <string> DisplayPromptAync(string title = null, string description = null, string text = null)
        {
            var         result = new TaskCompletionSource <string>();
            var         alert  = UIAlertController.Create(title ?? string.Empty, description, UIAlertControllerStyle.Alert);
            UITextField input  = null;

            alert.AddAction(UIAlertAction.Create(AppResources.Cancel, UIAlertActionStyle.Cancel, x =>
            {
                result.TrySetResult(null);
            }));
            alert.AddAction(UIAlertAction.Create(AppResources.Ok, UIAlertActionStyle.Default, x =>
            {
                result.TrySetResult(input.Text ?? string.Empty);
            }));
            alert.AddTextField(x =>
            {
                input      = x;
                input.Text = text ?? string.Empty;
            });
            var vc = GetPresentedViewController();

            vc?.PresentViewController(alert, true, null);
            return(result.Task);
        }
Пример #3
0
        void TimeLineLoaded(IAsyncResult result)
        {
            var request = result.AsyncState as HttpWebRequest;

            Busy = false;

            try {
                var response = request.EndGetResponse(result);
                var stream   = response.GetResponseStream();


                var root = CreateDynamicContent(XDocument.Load(new XmlTextReader(stream)));
                InvokeOnMainThread(delegate {
                    var tweetVC = new DialogViewController(root, true);
                    navigation.PushViewController(tweetVC, true);
                });
            } catch (WebException e) {
                InvokeOnMainThread(delegate {
                    var alertController = UIAlertController.Create("Error", "Code: " + e.Status, UIAlertControllerStyle.Alert);
                    alertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (obj) => { }));
                    window.RootViewController.PresentViewController(alertController, true, null);
                });
            }
        }
Пример #4
0
        public Task <string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons)
        {
            var result = new TaskCompletionSource <string>();
            var alert  = UIAlertController.Create(title ?? string.Empty, message, UIAlertControllerStyle.Alert);

            if (!string.IsNullOrWhiteSpace(cancel))
            {
                alert.AddAction(UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, x =>
                {
                    result.TrySetResult(cancel);
                }));
            }
            foreach (var button in buttons)
            {
                alert.AddAction(UIAlertAction.Create(button, UIAlertActionStyle.Default, x =>
                {
                    result.TrySetResult(button);
                }));
            }
            var vc = GetPresentedViewController();

            vc?.PresentViewController(alert, true, null);
            return(result.Task);
        }
Пример #5
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            string translatedNumber = "";

            TranslateButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                translatedNumber = PhoneTranslator.ToNumber(PhoneTextNumber.Text);

                PhoneTextNumber.ResignFirstResponder();

                if (translatedNumber == "")
                {
                    CallButton.SetTitle("Call", UIControlState.Normal);
                    CallButton.Enabled = false;
                }
                else
                {
                    CallButton.SetTitle("Call" + translatedNumber, UIControlState.Normal);
                    CallButton.Enabled = true;
                }
            };

            CallButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                var url = new NSUrl("tel:" + translatedNumber);
                if (UIApplication.SharedApplication.OpenUrl(url))
                {
                    var alert = UIAlertController.Create("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            };
        }
Пример #6
0
        void PromptUserForStorageOption()
        {
            string title   = "Choose Storage Option";
            string message = "Do you want to store documents in iCloud or only on this device?";
            string localOnlyActionTitle = "Local Only";
            string cloudActionTitle     = "iCloud";

            UIAlertController storageController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

            UIAlertAction localOption = UIAlertAction.Create(localOnlyActionTitle, UIAlertActionStyle.Default, action => {
                AppConfig.SharedAppConfiguration.StorageOption = StorageType.Local;
            });

            storageController.AddAction(localOption);

            UIAlertAction cloudOption = UIAlertAction.Create(cloudActionTitle, UIAlertActionStyle.Default, action => {
                AppConfig.SharedAppConfiguration.StorageOption = StorageType.Cloud;
                AppConfig.SharedAppConfiguration.StoreUbiquityIdentityToken();
            });

            storageController.AddAction(cloudOption);

            PresentViewController(storageController, true, null);
        }
Пример #7
0
        private void ShowMissionOptions(object sender, EventArgs eventArgs)
        {
            // Create the view controller that will present the list of missions.
            UIAlertController missionSelectionAlert = UIAlertController.Create("Select a mission", "", UIAlertControllerStyle.ActionSheet);

            // Needed to prevent a crash on iPad.
            UIPopoverPresentationController presentationPopover = missionSelectionAlert.PopoverPresentationController;

            if (presentationPopover != null)
            {
                presentationPopover.SourceView = View;
                presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
            }

            // Add an option for each mission.
            foreach (string item in _missionToItemId.Keys)
            {
                // Selecting the mission will call the ChangeMission method.
                missionSelectionAlert.AddAction(UIAlertAction.Create(item, UIAlertActionStyle.Default, async action => await ChangeMission(item)));
            }

            // Show the alert.
            PresentViewController(missionSelectionAlert, true, null);
        }
        // Show an alert with an "Okay" and "Cancel" button.
        private void ShowOkayCancelAlert()
        {
            var title             = "A Short Title is Best".Localize();
            var message           = "A message should be a short, complete sentence.".Localize();
            var cancelButtonTitle = "Cancel".Localize();
            var otherButtonTitle  = "OK".Localize();

            var alertCotroller = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

            // Create the actions.
            var cancelAction = UIAlertAction.Create(cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
                Console.WriteLine("The 'Okay/Cancel' alert's cancel action occured.");
            });

            var otherAction = UIAlertAction.Create(otherButtonTitle, UIAlertActionStyle.Default, alertAction => {
                Console.WriteLine("The 'Okay/Cancel' alert's other action occured.");
            });

            // Add the actions.
            alertCotroller.AddAction(cancelAction);
            alertCotroller.AddAction(otherAction);

            PresentViewController(alertCotroller, true, null);
        }
Пример #9
0
        public Task <string> Display(string title, string message, string firstButton, string secondButton, string cancel)
        {
            var taskCompletionSource = new TaskCompletionSource <string>();
            var alerController       = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

            alerController.AddAction(UIAlertAction.Create(firstButton, UIAlertActionStyle.Default, alert =>
            {
                taskCompletionSource.SetResult(firstButton);
            }));

            alerController.AddAction(UIAlertAction.Create(secondButton, UIAlertActionStyle.Default, alert =>
            {
                taskCompletionSource.SetResult(secondButton);
            }));

            alerController.AddAction(UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, alert =>
            {
                taskCompletionSource.SetResult(cancel);
            }));

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alerController, animated: true, completionHandler: null);

            return(taskCompletionSource.Task);
        }
Пример #10
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)
        {
            var         result = new TaskCompletionSource <string>();
            var         alert  = UIAlertController.Create(title ?? string.Empty, description, UIAlertControllerStyle.Alert);
            UITextField input  = null;

            okButtonText     = okButtonText ?? AppResources.Ok;
            cancelButtonText = cancelButtonText ?? AppResources.Cancel;
            alert.AddAction(UIAlertAction.Create(cancelButtonText, UIAlertActionStyle.Cancel, x =>
            {
                result.TrySetResult(null);
            }));
            alert.AddAction(UIAlertAction.Create(okButtonText, UIAlertActionStyle.Default, x =>
            {
                result.TrySetResult(input.Text ?? string.Empty);
            }));
            alert.AddTextField(x =>
            {
                input      = x;
                input.Text = text ?? string.Empty;
                if (numericKeyboard)
                {
                    input.KeyboardType = UIKeyboardType.NumberPad;
                }
                if (!ThemeHelpers.LightTheme)
                {
                    input.KeyboardAppearance = UIKeyboardAppearance.Dark;
                }
            });
            var vc = GetPresentedViewController();

            vc?.PresentViewController(alert, true, null);
            return(result.Task);
        }
Пример #11
0
        public async Task NotificationLaunched(string pokemonID, DateTime expires, float lat, float lon)
        {
            if (expires < DateTime.UtcNow)
            {
                var alert = UIAlertController.Create("Pokemon expired", "Looks like that Pokemon has despawned.", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
            else
            {
                settings.PokemonEnabled = true;
                MKCoordinateSpan span = new MKCoordinateSpan(Utility.MilesToLatitudeDegrees(0.7), Utility.MilesToLongitudeDegrees(0.7, lat));
                var coords            = new CLLocationCoordinate2D(lat, lon);
                var reg = new MKCoordinateRegion(coords, span);
                map.SetRegion(reg, true);
                await ServiceLayer.SharedInstance.LoadData();

                var poke = map.Annotations.OfType <Pokemon>().Where(p => p.id == pokemonID).FirstOrDefault();
                if (poke != null)
                {
                    map.SelectAnnotation(poke, true);
                }
            }
        }
        private void Open()
        {
            var controller = new SupportRotationAlertController(_actionHeaderTitle, _actionHeaderMessage,
                                                                UIAlertControllerStyle.ActionSheet);

            foreach (var action in _actions)
            {
                controller.AddAction(UIAlertAction.Create(action.Title,
                                                          action.CommandActionStyle.ToNative(),
                                                          action.Command.Execute));
            }

            if (!Equals(TintColor, UIColor.Clear))
            {
                controller.View.TintColor = TintColor;
            }

            _viewLocator.GetTopViewController().PresentViewController(controller, true, null);

            if (!Equals(TintColor, UIColor.Clear))
            {
                controller.View.TintColor = TintColor;
            }
        }
Пример #13
0
        async partial void btnEnter_TouchUpInside(UIKit.UIButton sender)
        {
            BTProgressHUD.Show("Checking your credentials...", -1, ProgressHUD.MaskType.Clear);

            if (string.Empty.Equals(txtUsername.Text))
            {
                BTProgressHUD.Dismiss();
                UIAlertView alert = new UIAlertView()
                {
                    Title   = "E-mail",
                    Message = "Please fill in the E-mail"
                };
                alert.AddButton("OK");
                alert.Show();
            }
            else if (string.Empty.Equals(txtPassword.Text))
            {
                BTProgressHUD.Dismiss();
                var alert = UIAlertController.Create("Password", "Please fill in the Password", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
            else
            {
                try
                {
                    UserLoginModel userLoginModel = new UserLoginModel(txtUsername.Text, txtPassword.Text);

                    tokenModel = await loginManager.GetAuthorizationToken(userLoginModel);

                    userModel = await loginManager.GetUserById(tokenModel.access_token);

                    CredentialsService.SaveCredentials(tokenModel, userModel);

                    Login();
                }
                catch (Exception ex)
                {
                    if (ex.Message.Equals("901"))
                    {
                        var alert = UIAlertController.Create("Login", "The user name or password is incorrect.", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(alert, true, null);
                    }
                    else if (ex.Message.Equals("903"))
                    {
                        var alert = UIAlertController.Create("Login", "An error occurred while sending the e-mail confirmation.", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(alert, true, null);
                    }
                    else if (ex.Message.Equals("905"))
                    {
                        var alert = UIAlertController.Create("Login", "The user e-mail is not confirmed. A new e-mail confirmation has been sent to user.", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(alert, true, null);
                    }
                    else
                    {
                        Utils.HandleException(ex);
                    }

                    BTProgressHUD.Dismiss();
                }
            }
        }
Пример #14
0
        void ActivateMore()
        {
            var displayed = new HashSet <nint>();

            for (var i = 0; i < _buttons.Count; i++)
            {
                var tag = _buttons[i].Tag;
                if (tag >= 0)
                {
                    displayed.Add(tag);
                }
            }

            var frame = _moreButton.Frame;

            if (!Forms.IsiOS8OrNewer)
            {
                var container = _moreButton.Superview;
                frame = new RectangleF(container.Frame.X, 0, frame.Width, frame.Height);
            }

            var x = frame.X - _scroller.ContentOffset.X;

            var path        = _tableView.IndexPathForCell(this);
            var rowPosition = _tableView.RectForRowAtIndexPath(path);
            var sourceRect  = new RectangleF(x, rowPosition.Y, rowPosition.Width, rowPosition.Height);

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                var actionSheet = new MoreActionSheetController();

                for (var i = 0; i < _cell.ContextActions.Count; i++)
                {
                    if (displayed.Contains(i))
                    {
                        continue;
                    }

                    var item     = _cell.ContextActions[i];
                    var weakItem = new WeakReference <MenuItem>(item);
                    var action   = UIAlertAction.Create(item.Text, UIAlertActionStyle.Default, a =>
                    {
                        _scroller.SetContentOffset(new PointF(0, 0), true);
                        MenuItem mi;
                        if (weakItem.TryGetTarget(out mi))
                        {
                            mi.Activate();
                        }
                    });
                    actionSheet.AddAction(action);
                }

                var controller = GetController();
                if (controller == null)
                {
                    throw new InvalidOperationException("No UIViewController found to present.");
                }

                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    var cancel = UIAlertAction.Create(StringResources.Cancel, UIAlertActionStyle.Cancel, null);
                    actionSheet.AddAction(cancel);
                }
                else
                {
                    actionSheet.PopoverPresentationController.SourceView = _tableView;
                    actionSheet.PopoverPresentationController.SourceRect = sourceRect;
                }

                controller.PresentViewController(actionSheet, true, null);
            }
            else
            {
                var d = new MoreActionSheetDelegate {
                    Scroller = _scroller, Items = new List <MenuItem>()
                };

                var actionSheet = new UIActionSheet(null, d);

                for (var i = 0; i < _cell.ContextActions.Count; i++)
                {
                    if (displayed.Contains(i))
                    {
                        continue;
                    }

                    var item = _cell.ContextActions[i];
                    d.Items.Add(item);
                    actionSheet.AddButton(item.Text);
                }

                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    var index = actionSheet.AddButton(StringResources.Cancel);
                    actionSheet.CancelButtonIndex = index;
                }

                actionSheet.ShowFrom(sourceRect, _tableView, true);
            }
        }
Пример #15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            string translatedNumber = "";

            TranslateButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                // Convert the phone number with text to a number
                // using PhoneTranslator.cs
                translatedNumber = PhoneTranslator.ToNumber(PhoneNumberText.Text);

                // 키보드 해제
                PhoneNumberText.ResignFirstResponder();

                if (translatedNumber == "")
                {
                    CallButton.SetTitle("Call", UIControlState.Normal);
                    CallButton.Enabled = false;
                }
                else
                {
                    CallButton.SetTitle("Call " + translatedNumber, UIControlState.Normal);
                    CallButton.Enabled = true;
                }
            };


            CallButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                PhoneNumbers.Add(translatedNumber);
                var url = new NSUrl("tel:" + translatedNumber);

                // Use URL handler with tel: prefix to invoke Apple's Phone app,
                // otherwise show an alert dialog

                if (!UIApplication.SharedApplication.OpenUrl(url))
                {
                    var alert = UIAlertController.Create("Not supported", "Scheme 'tel:' is not supported on this device", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            };

            //Segue 없이 탐색
            //CallHistoryButton.TouchUpInside += (object sender, EventArgs e) =>
            //{
            //    CallHistoryController callHistory = this.Storyboard.InstantiateViewController("CallHistoryController") as CallHistoryController;
            //    if (callHistory != null)
            //    {
            //        callHistory.PhoneNumbers = PhoneNumbers;
            //        this.NavigationController.PushViewController(callHistory, true);
            //    }
            //};

            //CAGradientLayer gradient = new CAGradientLayer();
            //gradient.Frame = this.CallButton.Frame;
            //gradient.Colors = new CGColor[] {UIColor.Yellow.CGColor , UIColor.Blue.CGColor};
            //gradient.StartPoint = new CGPoint(0.0, 0.5);
            //gradient.EndPoint = new CGPoint(0.5, 0.5);
            //gradient.Locations = new NSNumber[] {Convert.NS(this.CallButton.Frame.Location.X), this.CallButton.Frame.Location.X };

            //CallButton.Layer.InsertSublayer(gradient, 0);
            //CallButton.Layer.CornerRadius = CallButton.Frame.Size.Height / 2;
            //CallButton.Layer.BorderWidth = 5.0f;
        }
        private void BuildInterface()
        {
            View.BackgroundColor = new UIImage("Images/fondoPrincipal.jpg").GetScaledImageBackground(View);

            var header = new Header(View.Frame.Width)
            {
                LocationTitle   = _assignmentVm.SelectedAssignment.CompanyName,
                LeftButtonImage = "Images/btn-atras.png",
                ButtonTouch     = async(sender, args) =>
                {
                    if (_assignmentVm.SelectedActivity.ActivityType == Enumerations.ActivityType.None)
                    {
                        _assignmentVm.SelectedAssignment.Activities.Remove(_assignmentVm.SelectedActivity);
                    }
                    else
                    {
                        if (_assignmentVm.SelectedActivity.IsRecording)
                        {
                            await _assignmentVm.StopAsync(willContinue : true);

                            _assignmentVm.SelectedActivity.IsRecording = true;
                        }
                        _assignmentVm.SelectedActivity.Traces.Add(new Trace
                        {
                            ActivityId    = _assignmentVm.SelectedActivity.Id,
                            ActivityState = _assignmentVm.SelectedActivity.State,
                            TraceDate     = DateTime.Now,
                            Longitude     = (decimal)_longitude,
                            Latitude      = (decimal)_latitude
                        });
                        await _assignmentVm.SaveActivityAsync();
                    }
                    _navigationService.GoBack();
                }
            };

            var principalData = new AssignmentDataView(View.Frame)
            {
                Frame = new CGRect(0, header.Frame.Y + header.Frame.Height, View.Frame.Width, 65)
            };

            _activityType = new ActivityFill
            {
                Title           = "Tipo de Actividad",
                BackgroundColor = UIColor.Clear,
                Frame           = new CGRect(10, principalData.Frame.Y + principalData.Frame.Height, View.Frame.Width, 40),
                Hit             = TouchActivityTypeButton
            };

            _description = new ActivityFill
            {
                Title           = "Decripción",
                BackgroundColor = UIColor.Clear,
                Frame           = new CGRect(10, _activityType.Frame.Y + _activityType.Frame.Height, View.Frame.Width - 20, 40),
                Hit             = TouchButtonDescription
            };

            _startDate = new ActivityDate
            {
                Title = "Fecha de Inicio",
                Frame = new CGRect(10, _description.Frame.Y + _description.Frame.Height, View.Frame.Width, 40)
            };

            _endDate = new ActivityDate
            {
                Title = "Fecha de Inicio",
                Frame = new CGRect(10, _startDate.Frame.Y + _startDate.Frame.Height, View.Frame.Width, 40)
            };

            _description.NewTitle = string.IsNullOrEmpty(_assignmentVm.SelectedActivity.Description)
                ? "+"
                : _assignmentVm.SelectedActivity.Description;
            _activityType.NewTitle = GetTypeName(_assignmentVm.SelectedActivity.ActivityType);
            _startDate.Date        = (_assignmentVm.SelectedActivity.StartDate != DateTime.MinValue)
                ? _assignmentVm.SelectedActivity.StartDate.ToString("dd/MM/yyyy hh:mm")
                : string.Empty;
            _endDate.Date = (_assignmentVm.SelectedActivity.EndDate != DateTime.MinValue)
                ? _assignmentVm.SelectedAssignment.EndDate.ToString("dd/MM/yyyy hh:mm")
                : string.Empty;

            if (_assignmentVm.SelectedActivity.IsRecording)
            {
                var elapsed = DateTime.Now - _assignmentVm.SelectedActivity.StartDate;
                _assignmentVm.SelectedActivity.Duration = _assignmentVm.SelectedActivity.Duration.Add(elapsed);
                _assignmentVm.RecordAsync();
            }

            _timerView = new UIView
            {
                Frame = new CGRect(View.Frame.Width / 2 - 70, _endDate.Frame.Y + _endDate.Frame.Height + 10, 160, 160)
            };

            _timespan = new UILabel
            {
                Frame     = new CGRect(0, 0, 160, 60),
                Font      = UIFont.FromName("Helvetica-Bold", 35),
                TextColor = UIColor.White,
                Text      = _assignmentVm.SelectedActivity.Duration.ToString(@"hh\:mm\:ss")
            };

            var timerButton = UIButton.FromType(UIButtonType.Custom);

            timerButton.Frame = new CGRect(View.Frame.Width / 2 - 120, _timespan.Frame.Height + 5, 70, 70);
            timerButton.SetImage(
                _assignmentVm.SelectedActivity.IsRecording
                        ? new UIImage("Images/btn-stop.png")
                        : new UIImage("Images/btn-play.png"), UIControlState.Normal);

            timerButton.Enabled        = _assignmentVm.SelectedAssignment.Status != Enumerations.AssignmentStatus.Complete;
            timerButton.TouchUpInside += (sender, args) =>
            {
                if (_assignmentVm.ActiveActivity != null &&
                    _assignmentVm.SelectedActivity.Id != _assignmentVm.ActiveActivity.Id)
                {
                    new UIAlertView(title: "Ferreyros", message: Constants.Messages.ActivityNotFinished, del: null,
                                    cancelButtonTitle: "OK", otherButtons: null).Show();
                    return;
                }
                _activityType.UserInteractionEnabled = false;
                _description.UserInteractionEnabled  = false;

                timerButton.Enabled          = false;
                _assignmentVm.ActiveActivity = !_assignmentVm.SelectedActivity.IsRecording
                    ? _assignmentVm.SelectedActivity
                    : null;

                var task = _assignmentVm.SelectedActivity.IsRecording
                    ? _assignmentVm.StopAsync()
                    : _assignmentVm.RecordAsync();

                timerButton.SetImage(
                    _assignmentVm.SelectedActivity.IsRecording
                        ? new UIImage("Images/btn-stop.png")
                        : new UIImage("Images/btn-play.png"), UIControlState.Normal);

                task.ContinueWith(_ =>
                {
                    BeginInvokeOnMainThread(() =>
                    {
                        timerButton.Enabled = _assignmentVm.ActiveActivity != null;
                    });
                });
            };
            //_timerView.Hidden = _assignmentVm.SelectedActivity.ActivityType == Enumerations.ActivityType.None;
            _timerView.AddSubviews(timerButton, _timespan);

            var notifyClient = UIButton.FromType(UIButtonType.Custom);

            notifyClient.SetImage(new UIImage("Images/send-mail.png"), UIControlState.Normal);
            notifyClient.SetTitle("Notificar el fin del servicio al Cliente", UIControlState.Normal);
            notifyClient.BackgroundColor          = UIColor.Clear;
            notifyClient.TitleLabel.Font          = UIFont.FromName("Helvetica-Light", 13f);
            notifyClient.TitleLabel.TextAlignment = UITextAlignment.Left;
            notifyClient.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
            notifyClient.TitleEdgeInsets          = new UIEdgeInsets(0, -60, 0, -150);
            notifyClient.Frame = new CGRect(40, _timerView.Frame.Y + _timerView.Frame.Height + 10, 80, 40);
            notifyClient.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
            //notifyClient.Enabled = _assignmentVm.SelectedActivity.State != Enumerations.ActivityState.Completed;
            notifyClient.TouchUpInside += (sender, args) =>
            {
                if (_assignmentVm.SelectedActivity.IsRecording)
                {
                    new UIAlertView(title: "Ferreyros", message: Constants.Messages.ActivityNotFinished, del: null,
                                    cancelButtonTitle: "OK", otherButtons: null).Show();
                    return;
                }

                var okCancelAlertController = UIAlertController.Create("Cerrar Servicio",
                                                                       "¿Con esta actividad se ha completado el servicio?, se enviará un correo al cliente informando.",
                                                                       UIAlertControllerStyle.Alert);

                okCancelAlertController.AddAction(UIAlertAction.Create("Si", UIAlertActionStyle.Default, async alert =>
                {
                    _assignmentVm.SelectedActivity.State = Enumerations.ActivityState.Completed;
                    await _assignmentVm.SaveActivityAsync();
                    await _assignmentVm.SendActivityEndsAssignmentMailAsync();
                    notifyClient.Enabled = false;
                }));
                okCancelAlertController.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Cancel, alert => { }));

                PresentViewController(okCancelAlertController, true, null);
            };

            var copyRight = new UILabel
            {
                Text          = "2016 Ferreyros | Derechos Reservados",
                TextAlignment = UITextAlignment.Center,
                TextColor     = UIColor.White,
                Font          = UIFont.FromName("Helvetica-Light", 10f),
                Frame         = new CGRect(0, View.Frame.Height - 30, View.Frame.Width, 20)
            };

            View.AddSubviews(header, principalData, _activityType, _description, _startDate, _endDate, _timerView,
                             notifyClient, copyRight);
        }
        private void TouchActivityTypeButton(object sender, EventArgs eventArgs)
        {
            var actionSheetAlert = UIAlertController.Create("Tipo de Actividad",
                                                            "Seleccione el tipo de actividad a realizar",
                                                            UIAlertControllerStyle.ActionSheet);

            actionSheetAlert.AddAction(UIAlertAction.Create("PREPARANDO VIAJE", UIAlertActionStyle.Default,
                                                            action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.PreparingTrip;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.PreparingTrip);
            }));
            actionSheetAlert.AddAction(UIAlertAction.Create("VIAJANDO", UIAlertActionStyle.Default,
                                                            async action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.Traveling;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.Traveling);
                if (_networkStatus != NetworkStatus.NotReachable)
                {
                    await _assignmentVm.SendActivityMailAsync();
                }
            }));
            actionSheetAlert.AddAction(UIAlertAction.Create("MANEJANDO", UIAlertActionStyle.Default,
                                                            async action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.Driving;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.Driving);
                if (_networkStatus != NetworkStatus.NotReachable)
                {
                    await _assignmentVm.SendActivityMailAsync();
                }
            }));
            actionSheetAlert.AddAction(UIAlertAction.Create("SERVICIO DE CAMPO", UIAlertActionStyle.Default,
                                                            action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.FieldService;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.FieldService);
            }));

            actionSheetAlert.AddAction(UIAlertAction.Create("ESPERA POR CLIENTE", UIAlertActionStyle.Default,
                                                            async action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.StandByClient;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.StandByClient);
                if (_networkStatus != NetworkStatus.NotReachable)
                {
                    await _assignmentVm.SendActivityMailAsync();
                }
            }));

            actionSheetAlert.AddAction(UIAlertAction.Create("ELABORACIÓN DE INFORME",
                                                            UIAlertActionStyle.Default,
                                                            action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.FieldReport;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.FieldReport);
            }));

            actionSheetAlert.AddAction(UIAlertAction.Create("ESPERA FESA", UIAlertActionStyle.Default,
                                                            async action =>
            {
                _assignmentVm.SelectedActivity.ActivityType = Enumerations.ActivityType.StandByFesa;
                _activityType.NewTitle = GetTypeName(Enumerations.ActivityType.StandByFesa);
                if (_networkStatus != NetworkStatus.NotReachable)
                {
                    await _assignmentVm.SendActivityMailAsync();
                }
            }));

            actionSheetAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, action => { }));

            var presentationPopover = actionSheetAlert.PopoverPresentationController;

            if (presentationPopover != null)
            {
                presentationPopover.SourceView = View;
                presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
            }

            PresentViewController(actionSheetAlert, true, null);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            posScanButton.TouchUpInside += async(object sender, EventArgs e) =>
            {
                var scanner = new ZXing.Mobile.MobileBarcodeScanner();
                var result  = await scanner.Scan();

                if (result != null)
                {
                    UIAlertView alert = new UIAlertView();
                    alert.Title = "Result";
                    alert.AddButton("OK");
                    alert.Message = result.ToString();
                    alert.Show();

                    barcode_list.Add(result.ToString()); //add a barcode
                }
            };

            memScanButton.TouchUpInside += async(object sender, EventArgs e) =>
            {
                var scanner = new ZXing.Mobile.MobileBarcodeScanner();
                var result  = await scanner.Scan();

                if (result != null)
                {
                    UIAlertView alert = new UIAlertView();
                    alert.Title = "Result";
                    alert.AddButton("OK");
                    alert.Message = result.ToString();
                    alert.Show();

                    barcode_list.Add(result.ToString()); //add a barcode
                }
            };


            //for the publish button
            doneButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                var emailMessenger = CrossMessaging.Current.EmailMessenger; //for sending email
                var choice         = UIAlertController.Create("Send List", "Do you want to send the list out as email?", UIAlertControllerStyle.Alert);

                //let the user choose want to write file or not
                //if yes
                choice.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                {
                    //create alert to get file name
                    var InfoInput = UIAlertController.Create("Details", "Fill in all the info", UIAlertControllerStyle.Alert);

                    //add text input
                    InfoInput.AddTextField(textField => { });
                    InfoInput.AddTextField(textField => { });
                    InfoInput.AddTextField(textField => { });
                    InfoInput.AddTextField(textField => { });

                    //placeholder
                    InfoInput.TextFields[0].Placeholder = "Title";
                    InfoInput.TextFields[1].Placeholder = "Event Name";
                    InfoInput.TextFields[2].Placeholder = "Year";
                    InfoInput.TextFields[3].Placeholder = "Location";

                    //Add Actions to get file name
                    InfoInput.AddAction(UIAlertAction.Create("Send", UIAlertActionStyle.Default, (UIAlertAction obj1) =>
                    {
                        title      = InfoInput.TextFields[0].Text; //get the title text from the textfield
                        event_name = InfoInput.TextFields[1].Text; //get the event_name text from the textfield
                        location   = InfoInput.TextFields[2].Text; //get the location text from the textfield
                        year       = InfoInput.TextFields[3].Text; //get the year text from the textfield


                        if (title != "" && event_name != "" && location != "" && year != "") //to avoid the filename is empty
                        {
                            //write all together for sending to email
                            sending_list = sending_list + "Event Name: " + event_name + '\n'; //for event name
                            sending_list = sending_list + "Location: " + location + '\n';     //for location
                            sending_list = sending_list + "Year: " + year + '\n';             //for year


                            for (int i = 0; i < barcode_list.Count; i++)
                            {
                                sending_list = sending_list + '\n' + count + '\t' + barcode_list[i].ToString();
                                count++;
                            }

                            //publish to email
                            if (emailMessenger.CanSendEmail)
                            {
                                // Alternatively use EmailBuilder fluent interface to construct more complex e-mail with multiple recipients, bcc, attachments etc.
                                var email = new EmailMessageBuilder()
                                            .To("to." + E_address)
                                            .Cc("")
                                            .Bcc(new[] { "" })
                                            .Subject(title)
                                            .Body(sending_list)
                                            .Build();

                                emailMessenger.SendEmail(email);
                            }

                            UIAlertView alert = new UIAlertView();
                            alert.Title       = "Notice";
                            alert.AddButton("OK");
                            alert.Message = "All the lists have sent to " + E_address; //successful message
                            alert.Show();

                            sending_list = "";    //clear all the sending list
                            barcode_list.Clear(); //clear the barcode list
                        }
                        else
                        {
                            UIAlertView alert = new UIAlertView();
                            alert.Title       = "Warning";
                            alert.AddButton("OK");
                            alert.Message = "Please insert all the info";
                            alert.Show();
                        }
                    }));

                    ShowViewController(InfoInput, null);  //present alert fileNameInput
                }));

                //if no for the choice
                choice.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                {
                    //nothing happen
                }));

                ShowViewController(choice, null); //present alert choice
            };
        }
Пример #19
0
        void PublishPost(NSObject sender)
        {
            // Prevents multiple posting, locks as soon as a post is made
            PostButton.Enabled = false;
            UIActivityIndicatorView indicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.Gray);

            indicator.StartAnimating();
            PostButton.CustomView = indicator;

            // Hides the keyboards and dispatches a UI update to show the upload progress
            HiddenText.EndEditing(true);
            TagField.EndEditing(true);
            ProgressBar.Hidden = false;

            // Creates post record type and initizalizes all of its values
            CKRecord newRecord = new CKRecord(Post.RecordType);

            newRecord [Post.FontKey]     = (NSString)ImageLabel.Font.Name;
            newRecord [Post.ImageRefKey] = new CKReference(ImageRecord.Record.Id, CKReferenceAction.DeleteSelf);
            newRecord [Post.TextKey]     = (NSString)HiddenText.Text;
            string[] tags = TagField.Text.ToLower().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            newRecord [Post.TagsKey] = NSArray.FromObjects(tags);

            Post newPost = new Post(newRecord);

            newPost.ImageRecord = ImageRecord;

            // Only upload image record if it is not on server, otherwise just upload the new post record
            CKRecord[] recordsToSave = ImageRecord.IsOnServer
                                ? new CKRecord[] { newRecord }
                                : new CKRecord[] { newRecord, ImageRecord.Record };
            // TODO: https://trello.com/c/A9T8Spyp second param is null
            CKModifyRecordsOperation saveOp = new CKModifyRecordsOperation(recordsToSave, new CKRecordID[0]);

            saveOp.PerRecordProgress = (CKRecord record, double progress) => {
                // Image record type is probably going to take the longest to upload. Reflect it's progress in the progress bar
                if (record.RecordType == Image.RecordType)
                {
                    InvokeOnMainThread(() => {
                        var val = (float)(progress * 0.95);
                        ProgressBar.SetProgress(val, true);
                    });
                }
            };

            // When completed it notifies the tableView to add the post we just uploaded, displays error if it didn't work
            saveOp.Completed = (CKRecord[] savedRecords, CKRecordID[] deletedRecordIDs, NSError operationError) => {
                Error errorResponse = HandleError(operationError);
                switch (errorResponse)
                {
                case Error.Success:
                    // Tells delegate to update so it can display our new post
                    InvokeOnMainThread(() => {
                        DismissViewController(true, null);
                        MainController.Submit(newPost);
                    });
                    break;

                case Error.Retry:
                    CKErrorInfo errorInfo  = new CKErrorInfo(operationError.UserInfo);
                    nint        retryAfter = errorInfo.RetryAfter.HasValue ? errorInfo.RetryAfter.Value : 3;
                    Console.WriteLine("Error: {0}. Recoverable, retry after {1} seconds", operationError.Description, retryAfter);
                    Task.Delay((int)retryAfter * 1000).ContinueWith(_ => PublishPost(sender));
                    break;

                case Error.Ignore:
                    Console.WriteLine("Error saving record: {0}", operationError.Description);

                    string errorTitle    = "Error";
                    string dismissButton = "Okay";
                    string errorMessage  = operationError.Code == (long)CKErrorCode.NotAuthenticated
                                                        ? "You must be logged in to iCloud in order to post"
                                                        : "Unrecoverable error with the upload, check console logs";

                    InvokeOnMainThread(() => {
                        UIAlertController alert = UIAlertController.Create(errorTitle, errorMessage, UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create(dismissButton, UIAlertActionStyle.Cancel, null));

                        PostButton.Enabled = true;
                        PresentViewController(alert, true, null);
                        ProgressBar.Hidden    = true;
                        PostButton.CustomView = null;
                    });
                    break;

                default:
                    throw new NotImplementedException();
                }
            };
            CKContainer.DefaultContainer.PublicCloudDatabase.AddOperation(saveOp);
        }
Пример #20
0
        // TODO: implement max size for floor picker
        ////public override void ViewWillTransitionToSize(CoreGraphics.CGSize toSize, UIKit.IUIViewControllerTransitionCoordinator coordinator)
        ////{
        ////    base.ViewWillTransitionToSize(toSize, coordinator);
        ////        if (UIDevice.CurrentDevice.Orientation.IsLandscape())
        ////    {
        ////    }
        ////}

        /// <summary>
        /// Overrides default behavior when view has loaded.
        /// </summary>
        public async override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.ViewModel.PropertyChanged += this.ViewModelPropertyChanged;

            try
            {
                await this.ViewModel.InitializeAsync();
            }
            catch (Exception ex)
            {
                var genericError = "An error has occured and map was not loaded. Please restart the app";

                this.InvokeOnMainThread(() =>
                {
                    var detailsController = UIAlertController.Create("Error Details", ex.Message, UIAlertControllerStyle.Alert);
                    detailsController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    var alertController = UIAlertController.Create("Error", genericError, UIAlertControllerStyle.Alert);
                    alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    alertController.AddAction(
                        UIAlertAction.Create(
                            "Details",
                            UIAlertActionStyle.Default,
                            (obj) => { this.PresentViewController(detailsController, true, null); }));
                    this.PresentViewController(alertController, true, null);
                });
            }

            // If the map does not have transportation networks, hide the directions button
            if (!this.MapView.Map.TransportationNetworks.Any())
            {
                this.DirectionsButton.Enabled   = false;
                this.DirectionsButton.TintColor = UIColor.White;
            }

            // Set borders and shadows on controls
            this.CurrentLocationButton.Layer.ShadowColor   = UIColor.Gray.CGColor;
            this.CurrentLocationButton.Layer.ShadowOpacity = 1.0f;
            this.CurrentLocationButton.Layer.ShadowRadius  = 6.0f;
            this.CurrentLocationButton.Layer.ShadowOffset  = new System.Drawing.SizeF(0f, 3f);
            this.CurrentLocationButton.Layer.MasksToBounds = false;

            this.FloorsTableView.Layer.ShadowColor   = UIColor.Gray.CGColor;
            this.FloorsTableView.Layer.ShadowOpacity = 1.0f;
            this.FloorsTableView.Layer.ShadowRadius  = 6.0f;
            this.FloorsTableView.Layer.ShadowOffset  = new System.Drawing.SizeF(0f, 3f);
            this.FloorsTableView.Layer.MasksToBounds = false;

            this.ContactCardView.Layer.ShadowColor   = UIColor.Gray.CGColor;
            this.ContactCardView.Layer.ShadowOpacity = 1.0f;
            this.ContactCardView.Layer.ShadowRadius  = 6.0f;
            this.ContactCardView.Layer.ShadowOffset  = new System.Drawing.SizeF(0f, 3f);
            this.ContactCardView.Layer.MasksToBounds = false;

            this.SearchToolbar.Layer.ShadowColor   = UIColor.Gray.CGColor;
            this.SearchToolbar.Layer.ShadowOpacity = 1.0f;
            this.SearchToolbar.Layer.ShadowRadius  = 6.0f;
            this.SearchToolbar.Layer.ShadowOffset  = new System.Drawing.SizeF(0f, 3f);
            this.SearchToolbar.Layer.MasksToBounds = false;

            // Remove mapview grid and set its background
            this.MapView.BackgroundGrid.GridLineWidth = 0;
            this.MapView.BackgroundGrid.Color         = System.Drawing.Color.WhiteSmoke;

            // Add a graphics overlay to hold the pins and route graphics
            var pinsGraphicOverlay = new GraphicsOverlay();

            pinsGraphicOverlay.Id = "PinsGraphicsOverlay";
            this.MapView.GraphicsOverlays.Add(pinsGraphicOverlay);

            var labelsGraphicOverlay = new GraphicsOverlay();

            labelsGraphicOverlay.Id = "LabelsGraphicsOverlay";
            this.MapView.GraphicsOverlays.Add(labelsGraphicOverlay);

            var routeGraphicsOverlay = new GraphicsOverlay();

            routeGraphicsOverlay.Id = "RouteGraphicsOverlay";
            this.MapView.GraphicsOverlays.Add(routeGraphicsOverlay);

            // TODO: The comments below were added on January 24. Check to see if the last letter disappears.
            // Handle the user moving the map
            this.MapView.NavigationCompleted += this.MapView_NavigationCompleted;

            // Handle the user tapping on the map
            this.MapView.GeoViewTapped += this.MapView_GeoViewTapped;

            // Handle the user double tapping on the map
            this.MapView.GeoViewDoubleTapped += this.MapView_GeoViewDoubleTapped;

            // Handle the user holding tap on the mapp
            this.MapView.GeoViewHolding += this.MapView_GeoViewHolding;

            this.MapView.LocationDisplay.LocationChanged += this.MapView_LocationChanged;

            // Handle text changing in the search bar
            this.LocationSearchBar.TextChanged += async(sender, e) =>
            {
                // Call to populate autosuggestions
                await GetSuggestionsFromLocatorAsync();
            };

            this.LocationSearchBar.SearchButtonClicked += async(sender, e) =>
            {
                var searchText = ((UISearchBar)sender).Text;

                // Dismiss keyboard
                ((UISearchBar)sender).EndEditing(true);

                // Dismiss autosuggestions table
                AutosuggestionsTableView.Hidden = true;
                await GetSearchedFeatureAsync(searchText);
            };
        }
Пример #21
0
            public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                tableView.DeselectRow(indexPath, true);
                tableView.EndEditing(true);

                if (_tableItems.Count() == 0)
                {
                    _controller.PerformSegue("loginAddSegue", this);
                    return;
                }

                var item = _tableItems.ElementAt(indexPath.Row);

                if (item == null)
                {
                    _controller.LoadingController.CompleteRequest(null);
                    return;
                }

                if (_controller.CanAutoFill() && !string.IsNullOrWhiteSpace(item.Password))
                {
                    _controller.LoadingController.CompleteUsernamePasswordRequest(item.Username, item.Password);
                }
                else if (!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password))
                {
                    var sheet = Dialogs.CreateActionSheet(item.Name, _controller);
                    if (!string.IsNullOrWhiteSpace(item.Username))
                    {
                        sheet.AddAction(UIAlertAction.Create(AppResources.CopyUsername, UIAlertActionStyle.Default, a =>
                        {
                            UIPasteboard clipboard = UIPasteboard.General;
                            clipboard.String       = item.Username;
                            var alert = Dialogs.CreateMessageAlert(AppResources.CopyUsername);
                            _controller.PresentViewController(alert, true, () =>
                            {
                                _controller.DismissViewController(true, null);
                            });
                        }));
                    }

                    if (!string.IsNullOrWhiteSpace(item.Password))
                    {
                        sheet.AddAction(UIAlertAction.Create(AppResources.CopyPassword, UIAlertActionStyle.Default, a =>
                        {
                            UIPasteboard clipboard = UIPasteboard.General;
                            clipboard.String       = item.Password;
                            var alert = Dialogs.CreateMessageAlert(AppResources.CopiedPassword);
                            _controller.PresentViewController(alert, true, () =>
                            {
                                _controller.DismissViewController(true, null);
                            });
                        }));
                    }

                    sheet.AddAction(UIAlertAction.Create(AppResources.Cancel, UIAlertActionStyle.Cancel, null));
                    _controller.PresentViewController(sheet, true, null);
                }
                else
                {
                    var alert = Dialogs.CreateAlert(null, AppResources.NoUsernamePasswordConfigured, AppResources.Ok);
                    _controller.PresentViewController(alert, true, null);
                }
            }
Пример #22
0
        void LoadImages()
        {
            // If we're already loading a set of images or there are no images left to load, just return
            lock (locker) {
                if (isLoadingBatch || firstThumbnailLoaded)
                {
                    return;
                }
                else
                {
                    isLoadingBatch = true;
                }
            }

            // If we have a cursor, continue where we left off, otherwise set up new query
            CKQueryOperation queryOp = null;

            if (imageCursor != null)
            {
                queryOp = new CKQueryOperation(imageCursor);
            }
            else
            {
                CKQuery thumbnailQuery = new CKQuery(Image.RecordType, NSPredicate.FromValue(true));
                thumbnailQuery.SortDescriptors = Utils.CreateCreationDateDescriptor(ascending: false);
                queryOp = new CKQueryOperation(thumbnailQuery);
            }

            // We only want to download the thumbnails, not the full image
            queryOp.DesiredKeys = new string[] {
                Image.ThumbnailKey
            };
            queryOp.ResultsLimit  = UpdateBy;
            queryOp.RecordFetched = (CKRecord record) => {
                ImageCollection.AddImageFromRecord(record);
                InvokeOnMainThread(() => {
                    loadingImages.StopAnimating();
                    ImageCollection.ReloadData();
                });
            };
            queryOp.Completed = (CKQueryCursor cursor, NSError error) => {
                Error errorResponse = HandleError(error);

                if (errorResponse == Error.Success)
                {
                    imageCursor    = cursor;
                    isLoadingBatch = false;
                    if (cursor == null)
                    {
                        firstThumbnailLoaded = true;                         // If cursor is nil, lock this method indefinitely (all images have been loaded)
                    }
                }
                else if (errorResponse == Error.Retry)
                {
                    // If there's no specific number of seconds we're told to wait, default to 3
                    Utils.Retry(() => {
                        // Resets so we can load images again and then goes to load
                        isLoadingBatch = false;
                        LoadImages();
                    }, error);
                }
                else if (errorResponse == Error.Ignore)
                {
                    // If we get an ignore error they're not often recoverable. I'll leave loadImages locked indefinitely (this is up to the developer)
                    Console.WriteLine("Error: {0}", error.Description);
                    string errorTitle    = "Error";
                    string dismissButton = "Okay";
                    string errorMessage  = "We couldn't fetch one or more of the thumbnails";

                    UIAlertController alert = UIAlertController.Create(errorTitle, errorMessage, UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create(dismissButton, UIAlertActionStyle.Cancel, null));
                    InvokeOnMainThread(() => PresentViewController(alert, true, null));
                }
            };

            PublicCloudDatabase.AddOperation(queryOp);
        }
Пример #23
0
            // This method fetches the whole ImageRecord that a user taps on and then passes it to the delegate
            public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
            {
                // If the user has already tapped on a thumbnail, prevent them from tapping any others
                if (controller.lockSelectThumbnail)
                {
                    return;
                }
                else
                {
                    controller.lockSelectThumbnail = true;
                }

                // Starts animating the thumbnail to indicate it is loading
                controller.ImageCollection.SetLoadingFlag(indexPath, true);

                // Uses convenience API to fetch the whole image record associated with the thumbnail that was tapped
                CKRecordID userSelectedRecordID = controller.ImageCollection.GetRecordId(indexPath);

                controller.PublicCloudDatabase.FetchRecord(userSelectedRecordID, (record, error) => {
                    // If we get a partial failure, we should unwrap it
                    if (error != null && error.Code == (long)CKErrorCode.PartialFailure)
                    {
                        CKErrorInfo info = new CKErrorInfo(error);
                        error            = info[userSelectedRecordID];
                    }

                    Error errorResponse = controller.HandleError(error);

                    switch (errorResponse)
                    {
                    case Error.Success:
                        controller.ImageCollection.SetLoadingFlag(indexPath, false);
                        Image selectedImage = new Image(record);
                        InvokeOnMainThread(() => {
                            controller.MasterController.GoTo(controller, selectedImage);
                        });
                        break;

                    case Error.Retry:
                        Utils.Retry(() => {
                            controller.lockSelectThumbnail = false;
                            ItemSelected(collectionView, indexPath);
                        }, error);
                        break;

                    case Error.Ignore:
                        Console.WriteLine("Error: {0}", error.Description);
                        string errorTitle       = "Error";
                        string errorMessage     = "We couldn't fetch the full size thumbnail you tried to select, try again";
                        string dismissButton    = "Okay";
                        UIAlertController alert = UIAlertController.Create(errorTitle, errorMessage, UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create(dismissButton, UIAlertActionStyle.Cancel, null));
                        InvokeOnMainThread(() => controller.PresentViewController(alert, true, null));
                        controller.ImageCollection.SetLoadingFlag(indexPath, false);
                        controller.lockSelectThumbnail = false;
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                });
            }
        public void showControl(string controlName)
        {
            Console.WriteLine(controlName);

            switch (controlName)
            {
            case UICONTROL_NAMES.textField:

                UITextField textField = new UITextField(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height / 3));
                textField.Text          = "Hey I am TextField!";
                textField.BorderStyle   = UITextBorderStyle.Line;
                textField.TextAlignment = UITextAlignment.Center;
                this.View.AddSubview(textField);

                break;

            case UICONTROL_NAMES.inputTextField:
                UITextField inputTextField = new UITextField(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, 50));
                inputTextField.BorderStyle   = UITextBorderStyle.RoundedRect;
                inputTextField.TextAlignment = UITextAlignment.Center;
                inputTextField.Placeholder   = "Enter your name";
                inputTextField.Delegate      = this;
                inputTextField.WeakDelegate  = this;

                inputTextField.AddTarget((sender, e) =>
                {
                    Console.WriteLine("Editing Begin");
                }, UIControlEvent.EditingDidBegin);

                inputTextField.AddTarget((sender, e) =>
                {
                    Console.WriteLine("Editing changed");
                }, UIControlEvent.EditingChanged);


                this.View.AddSubview(inputTextField);
                break;

            case UICONTROL_NAMES.button:

                UIButton button = new UIButton(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, 50));
                button.SetTitleColor(UIColor.Black, UIControlState.Normal);
                button.SetTitle("Sample Button", UIControlState.Normal);
                button.Layer.BorderColor    = UIColor.Brown.CGColor;
                button.Layer.BorderWidth    = 10;
                button.TitleLabel.TextColor = UIColor.Blue;
                button.TouchUpInside       += delegate
                {
                    new UIAlertView("Touch1", "TouchUpInside handled", null, "OK", null).Show();
                };
                this.View.AddSubview(button);


                break;

            case UICONTROL_NAMES.toolBar:

                UIToolbar toolbar = new UIToolbar(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, 50));
                toolbar.Alpha = 1;

                UIBarButtonItem barButtonItem = new UIBarButtonItem("Bar1", UIBarButtonItemStyle.Done, null);
                barButtonItem.Title = "Bar1";

                UIBarButtonItem barButtonItem2 = new UIBarButtonItem("Bar1", UIBarButtonItemStyle.Bordered, null);
                barButtonItem.Title = "Bar2";


                var items = new UIBarButtonItem[2];
                items[0] = barButtonItem;
                items[1] = barButtonItem2;

                toolbar.SetItems(items, true);
                this.View.AddSubview(toolbar);
                break;

            case UICONTROL_NAMES.statusBar:

                UINavigationBar nav = this.NavigationController?.NavigationBar;

                nav.BarTintColor        = UIColor.Red;
                nav.TintColor           = UIColor.White;
                nav.TitleTextAttributes = new UIStringAttributes()
                {
                    ForegroundColor   = UIColor.Red,
                    KerningAdjustment = 3
                };


                this.SetNeedsStatusBarAppearanceUpdate();
                UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;


                break;

            case UICONTROL_NAMES.navigationBar:
                UINavigationBar navigationBar = this.NavigationController?.NavigationBar;
                navigationBar.BarTintColor = UIColor.LightGray;
                //navigationBar.TintColor = UIColor.White;
                navigationBar.TopItem.Title = "Sample Nav";

                break;

            case UICONTROL_NAMES.tabBar:

                UITabBar tabBar = new UITabBar(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, 50));

                var tabBarItems = new UITabBarItem[3];
                for (int i = 0; i < 3; i++)
                {
                    var tabBarItem = new UITabBarItem("TAB " + i, null, i);
                    tabBarItems[i] = tabBarItem;
                }

                tabBar.Items       = tabBarItems;
                tabBar.ItemSpacing = 10;

                tabBar.ItemSelected += (object sender, UITabBarItemEventArgs e) =>
                {
                    Console.WriteLine($"{e.Item} has selected");
                    if (e.Item.Tag == 0)
                    {
                        new UIAlertView(e.Item.Tag.ToString(), "ItemSelected handled", null, "OK", null).Show();
                    }
                    else if (e.Item.Tag == 1)
                    {
                        new UIAlertView(e.Item.Tag.ToString(), "ItemSelected handled", null, "OK", null).Show();
                    }
                    else if (e.Item.Tag == 2)
                    {
                        new UIAlertView(e.Item.Tag.ToString(), "ItemSelected handled", null, "OK", null).Show();
                    }
                };
                this.View.AddSubview(tabBar);

                break;

            case UICONTROL_NAMES.imageView:
                UIImageView imageView = new UIImageView(new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height / 3));
                imageView.BackgroundColor = UIColor.Blue;
                imageView.Image           = UIImage.FromFile("mac.png");
                this.View.AddSubview(imageView);
                break;

            case UICONTROL_NAMES.scrollView:
                UIScrollView scrollView = new UIScrollView(new CoreGraphics.CGRect(10, 100, this.View.Frame.Size.Width - 20, this.View.Frame.Size.Height * 1.5));
                scrollView.AlwaysBounceVertical = true;
                CGSize size = new CGSize(this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height * 1.5);
                scrollView.ContentSize     = size;
                scrollView.BackgroundColor = UIColor.LightGray;

                UILabel scrollText = new UILabel();
                scrollText.Frame = new CoreGraphics.CGRect(5, scrollView.Frame.Y, scrollView.Frame.Size.Width - 10, scrollView.Frame.Size.Height - 50);
                scrollText.Text  = "By the 4th century BCE, the late Achaemenid period, the inscriptions of Artaxerxes II and Artaxerxes III differ enough from the language of Darius' inscriptions to be called a pre-Middle Persian, or post-Old Persian.[14] Old Persian subsequently evolved into Middle Persian, which is in turn the ancestor of New Persian. Professor Gilbert Lazard, a famous Iranologist and the author of the book Persian Grammar states: The language known as New Persian, which usually is called at this period (early Islamic times) by the name of Parsi-Dari, can be classified linguistically as a continuation of Middle Persian, the official religious and literary language of Sassanian Iran, itself a continuation of Old Persian, the language of the Achaemenids. Unlike the other languages and dialects, ancient and modern, of the Iranian group such as Avestan, Parthian, Soghdian, Kurdish, Pashto, etc., Old, Middle and New Persian represent one and the same language at three states of its history. It had its origin in Fars and is differentiated by dialectical features, still easily recognizable from the dialect prevailing in north-western and eastern Iran. Middle Persian, also sometimes called Pahlavi, is a direct continuation of old Persian and was used as the written official language of the country.[16][17] Comparison of the evolution at each stage of the language shows great simplification in grammar and syntax. However, New Persian is a direct descendent of Middle and Old Persian.[18]";
                scrollText.Lines = 0;

                scrollView.AddSubview(scrollText);
                this.View.AddSubview(scrollView);
                break;

            case UICONTROL_NAMES.tableView:

                UITableView tableView = new UITableView();
                tableView.Frame           = new CGRect(0, 100, this.View.Frame.Size.Width, this.View.Frame.Size.Height);
                tableView.DataSource      = this;
                tableView.Delegate        = this;
                tableView.AllowsSelection = true;
                this.View.AddSubview(tableView);
                break;

            case UICONTROL_NAMES.collectionView:
                UICollectionViewFlowLayout collectionViewFlowLayout = new UICollectionViewFlowLayout();

                collectionViewFlowLayout.ItemSize = new CGSize(this.View.Bounds.Size.Width, this.View.Bounds.Size.Height);

                UICollectionView collectionView = new UICollectionView(frame: this.View.Bounds, layout: collectionViewFlowLayout);
                collectionView.Delegate        = this;
                collectionView.DataSource      = this;
                collectionView.BackgroundColor = UIColor.Cyan;


                collectionView.RegisterClassForCell(typeof(MyCollectionViewCell), "MyCollectionViewCell");

                this.View.AddSubview(collectionView);

                break;

            case UICONTROL_NAMES.splitView:
                Console.WriteLine("Better try again");


                break;

            case UICONTROL_NAMES.textView:

                UITextView textView = new UITextView();
                textView.Frame         = new CGRect(25, 100, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height * 1.5);
                textView.Text          = "The name India is derived from Indus, which originates from the Old Persian word Hindu.[24] The latter term stems from the Sanskrit word Sindhu, which was the historical local appellation for the Indus River.[25] The ancient Greeks referred to the Indians as Indoi (Ἰνδοί), which translates as The people of the Indus.The geographical term Bharat, which is recognised by the Constitution of India as an official name for the country,[27] is used by many Indian languages in its variations. \n\n It is a modernisation of the historical name Bharatavarsha, which traditionally referred to the Indian subcontinent and gained increasing currency from the mid-19th century as a native name for India.[28][29] \n Scholars believe it to be named after the Vedic tribe of Bhāratas in the second millennium BCE.[30] It is also traditionally associated with the rule of the legendary emperor Bharata.[31] The Hindu text Skanda Purana states that the region was named Bharat after Bharata Chakravartin.Gaṇarājya(literally, people's State) is the Sanskrit/Hindi term for republic dating back to ancient times. Hindustan([ɦɪnd̪ʊˈst̪aːn](About this sound listen)) is a Persian name for India dating back to the 3rd century BCE.It was introduced into India by the Mughals and widely used since then. \n \n Its meaning varied, referring to a region that encompassed northern India and Pakistan or India in its entirety.[28][29][35] Currently, the name may refer to either the northern part of India or the entire country";
                textView.ScrollEnabled = true;

                var attributedText = new NSMutableAttributedString(textView.Text);
                attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Red, new NSRange(0, textView.Text.Length));
                textView.AttributedText = attributedText;
                this.View.AddSubview(textView);

                break;

            case UICONTROL_NAMES.viewTransition:

                UIView view1 = new UIView(frame: new CGRect(25, this.View.Frame.Size.Height / 4, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height / 6));
                view1.BackgroundColor = UIColor.Red;
                this.View.AddSubview(view1);

                UIView view2 = new UIView(frame: new CGRect(25, this.View.Frame.Size.Height / 2, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Height / 6));
                view2.BackgroundColor = UIColor.Red;
                this.View.AddSubview(view2);

                UIButton transitionButton = new UIButton(frame: new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 1.3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 5));
                transitionButton.SetTitle("Show transition", UIControlState.Normal);
                transitionButton.BackgroundColor = UIColor.Brown;
                transitionButton.TitleLabel.Text = "Show transition";

                transitionButton.TouchUpInside += delegate
                {
                    if (transitionButton.Selected == true)
                    {
                        transitionButton.Selected = false;
                        UIView.Transition(view1, 0.4, UIViewAnimationOptions.TransitionCrossDissolve, null, () =>
                        {
                            view1.BackgroundColor = UIColor.Blue;
                            view2.BackgroundColor = UIColor.Red;
                        });
                    }
                    else
                    {
                        transitionButton.Selected = true;

                        UIView.Transition(view1, 0.4, UIViewAnimationOptions.TransitionCrossDissolve, null, () =>
                        {
                            view1.BackgroundColor = UIColor.Red;
                            view2.BackgroundColor = UIColor.Blue;
                        });
                    }
                };
                this.View.AddSubview(transitionButton);

                break;

            case UICONTROL_NAMES.picker:

                UILabel valueLabel = new UILabel(frame: new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 1.3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 5));
                valueLabel.BackgroundColor = UIColor.Brown;
                valueLabel.Text            = "Show transition";

                UIPickerView pickerView = new UIPickerView();
                pickerView.Frame      = new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 3);
                pickerView.DataSource = this;
                pickerView.Delegate   = this;
                this.View.AddSubview(pickerView);

                break;

            case UICONTROL_NAMES.switches:

                UILabel switchStatusLabel = new UILabel(frame: new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 1.3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 5));
                switchStatusLabel.BackgroundColor = UIColor.Black;
                switchStatusLabel.TextAlignment   = UITextAlignment.Center;
                switchStatusLabel.TextColor       = UIColor.White;
                switchStatusLabel.Text            = "Switch Status";
                this.View.AddSubview(switchStatusLabel);

                UISwitch switchObject = new UISwitch();
                switchObject.Frame         = new CoreGraphics.CGRect(this.View.Frame.Size.Width / 2, this.View.Frame.Size.Height / 3, 10f, 10f);
                switchObject.ValueChanged += delegate {
                    if (switchObject.On)
                    {
                        Console.WriteLine("TRUE");
                        switchStatusLabel.BackgroundColor = UIColor.Green;
                        switchStatusLabel.Text            = "Switch ON";
                    }
                    else
                    {
                        Console.WriteLine("FALSE");
                        switchStatusLabel.BackgroundColor = UIColor.Red;
                        switchStatusLabel.Text            = "Switch OFF";
                    }
                };
                this.View.AddSubview(switchObject);

                break;

            case UICONTROL_NAMES.sliders:

                UILabel sliderStatusLabel = new UILabel(frame: new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 1.3, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 5));
                sliderStatusLabel.TextAlignment   = UITextAlignment.Center;
                sliderStatusLabel.TextColor       = UIColor.White;
                sliderStatusLabel.BackgroundColor = UIColor.Blue;
                sliderStatusLabel.Text            = "Slider Value";
                this.View.AddSubview(sliderStatusLabel);


                UISlider slider = new UISlider(frame: new CoreGraphics.CGRect(25, this.View.Frame.Size.Height / 2, this.View.Frame.Size.Width - 50, this.View.Frame.Size.Width / 5));
                slider.MinValue = 0;
                slider.MaxValue = 100;
                slider.MinimumTrackTintColor = UIColor.FromRGB(0xE6, 0x00, 0x06);
                slider.ThumbTintColor        = UIColor.Red;
                slider.MinimumTrackTintColor = UIColor.Orange;
                slider.MaximumTrackTintColor = UIColor.Yellow;

                slider.ValueChanged += delegate {
                    sliderStatusLabel.Text = "Slider Value :" + slider.Value.ToString();
                };

                this.View.AddSubview(slider);


                break;

            case UICONTROL_NAMES.alerts:

                var alert = UIAlertController.Create("Sample Alert", "Now You are on Visual Studio with Xamarin.iOS", UIAlertControllerStyle.ActionSheet);

                // set up button event handlers
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(true)));
                alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(false)));
                //
                //      var userClickedOk = await ShowOKCancel(this, "Action Sheet Title", " It is just awesome!");
                // go on to use the result in some way

                //if (userClickedOk)
                //{
                //    Console.WriteLine("Clicked on Okay");
                //}
                //else
                //{

                //    Console.WriteLine("Clicked on Cancel");
                //};


                // show it
                this.PresentViewController(alert, true, null);
                break;

            default:
                Console.WriteLine("Invalid grade");
                break;
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NSNotificationCenter.DefaultCenter.AddObserver((NSString)"ReloadPage", reloadPage);



            var db = BankRepository.Connection();

            AccountNameLabel.Text = Account.Name;
            BalanceLabel.Text     = "$" + Account.Balance.ToString();


            TransactionTableView.Source = new AccountTransactionTableDataSource(this);

            BackButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                DismissModalViewController(true);
            };

            DepositButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                TransactionViewController transactionViewController =
                    this.Storyboard.InstantiateViewController("TransactionViewController") as TransactionViewController;

                if (transactionViewController != null)
                {
                    transactionViewController.ModalTransitionStyle   = UIModalTransitionStyle.CoverVertical;
                    transactionViewController.ModalPresentationStyle = UIModalPresentationStyle.Automatic;
                    transactionViewController.account         = Account;
                    transactionViewController.TransactionType = "Deposit";

                    PresentViewController(transactionViewController, true, null);
                }
            };

            WithdrawlButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                TransactionViewController transactionViewController =
                    this.Storyboard.InstantiateViewController("TransactionViewController") as TransactionViewController;

                if (transactionViewController != null)
                {
                    transactionViewController.ModalTransitionStyle   = UIModalTransitionStyle.CoverVertical;
                    transactionViewController.ModalPresentationStyle = UIModalPresentationStyle.Automatic;
                    transactionViewController.account         = Account;
                    transactionViewController.TransactionType = "Withdrawal";

                    PresentViewController(transactionViewController, true, null);
                }
            };

            QuickDepositButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                List <QuickDeposit> quickDeposits = db.CreateCommand("SELECT * FROM QuickDepositTypes").ExecuteQuery <QuickDeposit>();
                string MenuString;

                if (quickDeposits.Count == 0)
                {
                    MenuString = "There are no Quick Deposit choices available. Add them by clicking on the wrench from the piggy bank list screen and selecting 'New Quick Deposit Choice'.";
                }
                else
                {
                    MenuString = "Select quick deposit option";
                }
                UIAlertController QuickDepositAlertController = UIAlertController.Create("Quick Deposit", MenuString, UIAlertControllerStyle.Alert);

                foreach (QuickDeposit quickDeposit in quickDeposits)
                {
                    string buttonText = quickDeposit.QuickDepositType + " $" + quickDeposit.Amount;

                    QuickDepositAlertController.AddAction(UIAlertAction.Create(buttonText, UIAlertActionStyle.Default, Action => {
                        QuickDepositTransaction(quickDeposit.QuickDepositType);
                    }));
                }
                QuickDepositAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
                PresentViewController(QuickDepositAlertController, true, null);
            };
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Make sure the user is logged in.

            /*
             * bool loggedIn = await EnsureLoggedInAsync();
             * if (!loggedIn)
             * {
             *  return;
             * }
             */

            // Disable the button to prevent errors.
            _takeMapOfflineButton.Enabled = false;

            // Show the loading indicator.
            _loadingIndicator.StartAnimating();

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception ex)
                {
                    // Ignore exceptions (files might be locked, for example).
                    Debug.WriteLine(ex);
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num);
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                _statusLabel.Text = "Taking map offline...";

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Show the configuration window.
                ShowConfigurationWindow(overrides);

                // Finish work once the user has configured the override.
                _overridesVC.FinishedConfiguring += async() =>
                {
                    // Hide the configuration UI.
                    _overridesVC.DismissViewController(true, null);

                    // Create the job with the parameters and output location.
                    _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                    // Handle the progress changed event for the job.
                    _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                    // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                    GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                    // Check for job failure (writing the output was denied, e.g.).
                    if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                    {
                        // Report failure to the user.
                        UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Check for errors with individual layers.
                    if (results.LayerErrors.Any())
                    {
                        // Build a string to show all layer errors.
                        System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                        foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                        {
                            errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                        }

                        // Show layer errors.
                        UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Display the offline map.
                    _myMapView.Map = results.OfflineMap;

                    // Apply the original viewpoint for the offline map.
                    _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                    // Enable map interaction so the user can explore the offline data.
                    _myMapView.InteractionOptions.IsEnabled = true;

                    // Change the title and disable the "Take map offline" button.
                    _statusLabel.Text             = "Map is offline";
                    _takeMapOfflineButton.Enabled = false;
                };
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }
Пример #27
0
        /// <summary>
        /// When view is tapped, clear the map of selection, close keyboard and bottom sheet
        /// </summary>
        /// <param name="sender">Sender element.</param>
        /// <param name="e">Eevent args.</param>
        private async void MapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            // Wait for double tap to fire
            await Task.Delay(500);

            // If view has been double tapped, set tapped to handled and flag back to false
            // If view has been tapped just once clear the map of selection, close keyboard and bottom sheet
            if (this.isViewDoubleTapped == true)
            {
                e.Handled = true;
                this.isViewDoubleTapped = false;
            }
            else
            {
                // If route card is visible, do not dismiss route
                if (this.RouteCard.Alpha == 1)
                {
                    // Create a new Alert Controller
                    UIAlertController actionSheetAlert = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet);

                    // Add Actions
                    actionSheetAlert.AddAction(UIAlertAction.Create("Clear Route", UIAlertActionStyle.Destructive, (action) => this.ClearRoute()));

                    actionSheetAlert.AddAction(UIAlertAction.Create("Keep Route", UIAlertActionStyle.Default, null));

                    // Required for iPad - You must specify a source for the Action Sheet since it is
                    // displayed as a popover
                    UIPopoverPresentationController presentationPopover = actionSheetAlert.PopoverPresentationController;
                    if (presentationPopover != null)
                    {
                        presentationPopover.SourceView = this.View;
                        presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
                    }

                    // Display the alert
                    this.PresentViewController(actionSheetAlert, true, null);
                }
                else
                {
                    // get the tap location in screen unit
                    var tapScreenPoint = e.Position;

                    var layer            = this.MapView.Map.OperationalLayers[AppSettings.CurrentSettings.RoomsLayerIndex];
                    var pixelTolerance   = 10;
                    var returnPopupsOnly = false;
                    var maxResults       = 1;

                    try
                    {
                        // Identify a layer using MapView, passing in the layer, the tap point, tolerance, types to return, and max result
                        IdentifyLayerResult idResults = await this.MapView.IdentifyLayerAsync(layer, tapScreenPoint, pixelTolerance, returnPopupsOnly, maxResults);

                        // create a picture marker symbol
                        var uiImagePin = UIImage.FromBundle("MapPin");
                        var mapPin     = this.ImageToByteArray(uiImagePin);
                        var roomMarker = new PictureMarkerSymbol(new RuntimeImage(mapPin));
                        roomMarker.OffsetY = uiImagePin.Size.Height * 0.65;

                        var identifiedResult = idResults.GeoElements.First();

                        // Create graphic
                        var mapPinGraphic = new Graphic(identifiedResult.Geometry.Extent.GetCenter(), roomMarker);

                        // Add pin to mapview
                        var graphicsOverlay = this.MapView.GraphicsOverlays["PinsGraphicsOverlay"];
                        graphicsOverlay.Graphics.Clear();
                        graphicsOverlay.Graphics.Add(mapPinGraphic);

                        // Get room attribute from the settings. First attribute should be set as the searcheable one
                        var roomAttribute = AppSettings.CurrentSettings.ContactCardDisplayFields[0];
                        var roomNumber    = identifiedResult.Attributes[roomAttribute];

                        if (roomNumber != null)
                        {
                            var employeeNameLabel = string.Empty;
                            if (AppSettings.CurrentSettings.ContactCardDisplayFields.Count > 1)
                            {
                                var employeeNameAttribute = AppSettings.CurrentSettings.ContactCardDisplayFields[1];
                                var employeeName          = identifiedResult.Attributes[employeeNameAttribute];
                                employeeNameLabel = employeeName as string ?? string.Empty;
                            }

                            this.ShowBottomCard(roomNumber.ToString(), employeeNameLabel.ToString(), false);
                        }
                        else
                        {
                            this.MapView.GraphicsOverlays["PinsGraphicsOverlay"].Graphics.Clear();
                            this.HideContactCard();
                        }
                    }
                    catch (Exception ex)
                    {
                        this.MapView.GraphicsOverlays["PinsGraphicsOverlay"].Graphics.Clear();
                        this.HideContactCard();
                    }

                    if (this.LocationSearchBar.IsFirstResponder == true)
                    {
                        this.LocationSearchBar.ResignFirstResponder();
                    }
                }
            }
        }
Пример #28
0
        private void OnStartButtonClicked(object sender, EventArgs e)
        {
            try
            {
                UIAlertController actionAlert = UIAlertController.Create(
                    "Select device location option", "", UIAlertControllerStyle.Alert);

                // Add actions to alert. Selecting an option displays different option for auto pan modes.
                actionAlert.AddAction(UIAlertAction.Create("On", UIAlertActionStyle.Default, (action) =>
                {
                    // Starts location display with auto pan mode set to Off
                    _myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Off;

                    //TODO Remove this IsStarted check https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/182
                    if (!_myMapView.LocationDisplay.IsEnabled)
                    {
                        _myMapView.LocationDisplay.IsEnabled = true;
                    }
                }));
                actionAlert.AddAction(UIAlertAction.Create("Re-center", UIAlertActionStyle.Default, (action) =>
                {
                    // Starts location display with auto pan mode set to Default
                    _myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;

                    //TODO Remove this IsStarted check https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/182
                    if (!_myMapView.LocationDisplay.IsEnabled)
                    {
                        _myMapView.LocationDisplay.IsEnabled = true;
                    }
                }));
                actionAlert.AddAction(UIAlertAction.Create("Navigation", UIAlertActionStyle.Default, (action) =>
                {
                    // Starts location display with auto pan mode set to Navigation
                    _myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;

                    //TODO Remove this IsStarted check https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/182
                    if (!_myMapView.LocationDisplay.IsEnabled)
                    {
                        _myMapView.LocationDisplay.IsEnabled = true;
                    }
                }));
                actionAlert.AddAction(UIAlertAction.Create("Compass", UIAlertActionStyle.Default, (action) =>
                {
                    // Starts location display with auto pan mode set to Compass Navigation
                    _myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.CompassNavigation;

                    //TODO Remove this IsStarted check https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/182
                    if (!_myMapView.LocationDisplay.IsEnabled)
                    {
                        _myMapView.LocationDisplay.IsEnabled = true;
                    }
                }));
                //present alert
                PresentViewController(actionAlert, true, null);
            }
            catch (Exception ex)
            {
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                PresentViewController(alert, true, null);
            }
        }
        // Handle the OnMapInfoEntered event from the item input UI.
        // MapSavedEventArgs contains the title, description, and tags that were entered.
        private async void MapItemInfoEntered()
        {
            // Get the current map.
            Map myMap = _myMapView.Map;

            try
            {
                // Show the activity indicator so the user knows work is happening.
                _activityIndicator.StartAnimating();

                // Get information entered by the user for the new portal item properties.
                string[] tags = _tags.Split(',');

                // 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.
                    UIAlertController alert = UIAlertController.Create("Saved map",
                                                                       "Saved " + _title + " to ArcGIS Online", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                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.
                    ((PortalItem)myMap.Item).SetThumbnail(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful.
                    UIAlertController alert = UIAlertController.Create("Updated map", "Saved changes to " + _title,
                                                                       UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            }
            catch (Exception)
            {
                // Report save error.
                UIAlertController alert = UIAlertController.Create("Error", "Unable to save " + _title,
                                                                   UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
            finally
            {
                // Hide the progress bar.
                _activityIndicator.StopAnimating();
            }
        }
Пример #30
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();
            System.Text.Encoding.GetEncoding(1252);
            ScrollViewAbout.ContentSize = new CGSize(0, View.Frame.Height + 1000);
            UIButtonPactiaCom.AddTarget(ButtonEventHandler, UIControlEvent.TouchUpInside);
            UIButtonContactSend.AddTarget(ButtonEventHandler, UIControlEvent.TouchUpInside);
            UIButtonAccepConditions.AddTarget(ButtonEventHandler, UIControlEvent.TouchUpInside);
            UIButtonCallUs.AddTarget(ButtonEventHandler, UIControlEvent.TouchUpInside);

            #region Gestures
            UITapGestureRecognizer UIViewBusiness0Tap = new UITapGestureRecognizer(() =>
            {
                VideoViewController viewController = this.Storyboard.InstantiateViewController("VideoViewControllerId") as VideoViewController;
                this.NavigationController.PushViewController(viewController, true);
            });
            UIImageViewPactiaVideo.UserInteractionEnabled = true;
            UIImageViewPactiaVideo.AddGestureRecognizer(UIViewBusiness0Tap);

            UITapGestureRecognizer UIViewFacebookTap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://www.facebook.com/pactiaoficial/");
            });
            UIImageViewFacebook.UserInteractionEnabled = true;
            UIImageViewFacebook.AddGestureRecognizer(UIViewFacebookTap);

            UITapGestureRecognizer UIViewInstagramTap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://www.instagram.com/pactiaoficial/");
            });
            UIImageViewInstagram.UserInteractionEnabled = true;
            UIImageViewInstagram.AddGestureRecognizer(UIViewInstagramTap);

            UITapGestureRecognizer UIViewLinkedlnTap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://www.linkedin.com/company/pactia");
            });
            UIImageViewLinkedln.UserInteractionEnabled = true;
            UIImageViewLinkedln.AddGestureRecognizer(UIViewLinkedlnTap);

            UITapGestureRecognizer UIViewYoutubeTap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://www.youtube.com/channel/UCFH_l8cOLR-1FiS021ena2Q");
            });
            UIImageViewYoutube.UserInteractionEnabled = true;
            UIImageViewYoutube.AddGestureRecognizer(UIViewYoutubeTap);

            UITapGestureRecognizer UIViewBusiness2Tap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://pactia.com/linea-negocio/comercio/");
            });
            UIViewBusiness2.UserInteractionEnabled = true;
            UIViewBusiness2.AddGestureRecognizer(UIViewBusiness2Tap);

            UITapGestureRecognizer UIViewBusiness3Tap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://pactia.com/linea-negocio/oficinas/");
            });
            UIViewBusiness3.UserInteractionEnabled = true;
            UIViewBusiness3.AddGestureRecognizer(UIViewBusiness3Tap);
            UITapGestureRecognizer UIViewBusiness4Tap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://pactia.com/linea-negocio/autoalmacenamiento/");
            });
            UIViewBusiness4.UserInteractionEnabled = true;
            UIViewBusiness4.AddGestureRecognizer(UIViewBusiness4Tap);
            UITapGestureRecognizer UIViewBusiness5Tap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://pactia.com/linea-negocio/hoteles/");
            });
            UIViewBusiness5.UserInteractionEnabled = true;
            UIViewBusiness5.AddGestureRecognizer(UIViewBusiness5Tap);
            UITapGestureRecognizer UIViewBusiness6Tap = new UITapGestureRecognizer(() =>
            {
                iOSFunctions.OpenUrl(@"https://pactia.com/linea-negocio/multifamily/");
            });
            UIViewBusiness6.UserInteractionEnabled = true;
            UIViewBusiness6.AddGestureRecognizer(UIViewBusiness6Tap);

            UITapGestureRecognizer UIViewBusiness7Tap = new UITapGestureRecognizer(() =>
            {
                BusinessLineContectViewController viewController = this.Storyboard.InstantiateViewController("BusinessLineContectViewControllerId") as BusinessLineContectViewController;
                viewController.BusinessName = "Logistica";
                viewController.Latitude     = "4.760737";
                viewController.Longitude    = "-74.165095";
                this.NavigationController.PushViewController(viewController, true);
            });
            UIViewBusiness1.UserInteractionEnabled = true;
            UIViewBusiness1.AddGestureRecognizer(UIViewBusiness7Tap);



            this.View.AddGestureRecognizer(new UITapGestureRecognizer(tap =>
            {
                View.EndEditing(true);
            })
            {
                NumberOfTapsRequired = 1
            });
            #endregion

            IsInternetConnectionAvailable = SharedFunctions.CheckInternetConnection();
            if (IsInternetConnectionAvailable == true)
            {
                try
                {
                    var bounds = UIScreen.MainScreen.Bounds;
                    loadingIndicator = new LoadingIndicator(bounds, "Cargando contenido...");
                    View.Add(loadingIndicator);
                    await Task.Delay(10);

                    LoadUILabelText(UILabelPactiaTitle, "CONÓCENOS");
                    UIImageViewPactiaVideo.Image = UIImage.FromFile("videobackground.jpg");

                    Galeria galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=01");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness1);
                    Lineas lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=01");
                    LoadUILabelText(UILabelBusiness1Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness1Description, lineas.Texto2);
                    UIImageViewBusiness1Logo.Image = UIImage.FromFile("logikalogo.png");

                    galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=02");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness2);
                    lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=02");
                    LoadUILabelText(UILabelBusiness2Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness2Description, lineas.Texto2);
                    UIImageViewBusiness2Logo.Image = UIImage.FromFile("logogranplaza.png");

                    galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=03");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness3);
                    lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=03");
                    LoadUILabelText(UILabelBusiness3Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness3Description, lineas.Texto2);
                    UIImageViewBusiness3Logo.Image = UIImage.FromFile("burologo.png");

                    galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=77");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness4);
                    lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=05");
                    LoadUILabelText(UILabelBusiness4Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness4Description, lineas.Texto2);
                    UIImageViewBusiness4Logo.Image = UIImage.FromFile("ustoragelogo.png");

                    galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=04");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness5);
                    lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=04");
                    LoadUILabelText(UILabelBusiness5Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness5Description, lineas.Texto2);

                    galeria = service.HttpGet <Galeria>(constants.Url, constants.GaleriaController, constants.GaleriaMethod, "code=78");
                    ImageService.Instance.LoadUrl(galeria.Url).Into(UIImageViewBusiness6);
                    lineas = service.HttpGet <Lineas>(constants.Url, constants.LineaController, constants.LineaMethod, "code=07");
                    LoadUILabelText(UILabelBusiness6Title, lineas.Nombre);
                    LoadUILabelText(UILabelBusiness6Description, lineas.Texto2);
                    UIButtonPactiaCom.Hidden = false;

                    var Panama      = new MKPointAnnotation();
                    var PanamaCoord = new CLLocationCoordinate2D(9.131443, -79.681025);
                    Panama.Title      = "Panamá";
                    Panama.Coordinate = PanamaCoord;

                    var Colombia      = new MKPointAnnotation();
                    var ColombiaCoord = new CLLocationCoordinate2D(5.156853, -74.039258);
                    Colombia.Title      = "Colombia";
                    Colombia.Coordinate = ColombiaCoord;

                    var Usa      = new MKPointAnnotation();
                    var UsaCoord = new CLLocationCoordinate2D(40.343302, -102.066399);
                    Usa.Title      = "Estados Unidos";
                    Usa.Coordinate = UsaCoord;

                    MKPointAnnotation[] CoordArray = new MKPointAnnotation[3];
                    CoordArray[0] = Panama;
                    CoordArray[1] = Colombia;
                    CoordArray[2] = Usa;
                    MKMapViewAbout.AddAnnotations(CoordArray);

                    var locationCoordinate = new CLLocationCoordinate2D(25.688297, -100.324346);
                    var coordinateSpan     = new MKCoordinateSpan(50, 80);
                    var coordinateRegion   = new MKCoordinateRegion(locationCoordinate, coordinateSpan);
                    MKMapViewAbout.SetRegion(coordinateRegion, true);
                    loadingIndicator.Hide();
                }
                catch (Exception ex)
                {
                    ExceptionAlert("Alerta", ex.Message);
                }
            }
            else
            {
                var okCancelAlertController = UIAlertController.Create("Alerta", "Por favor verifique su conexión a internet e intenta nuevamente", UIAlertControllerStyle.Alert);
                okCancelAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, alert => Environment.Exit(0)));
                PresentViewController(okCancelAlertController, true, null);
            }
            float scrollViewHeight = 0.0f;
            float scrollViewWidth  = 0.0f;
            foreach (UIView view in ScrollViewAbout.Subviews)
            {
                scrollViewWidth  += (float)view.Frame.Size.Width;
                scrollViewHeight += (float)view.Frame.Size.Height;
            }
            ScrollViewAbout.ContentSize = new CGSize(0, scrollViewHeight + View.Frame.Height + 1500);
        }