예제 #1
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            namelbl.TextColor = UIColor.FromRGB(112, 112, 112);



            NavigationController.NavigationBarHidden = true;

            var screenTap = new UITapGestureRecognizer(() =>
            {
                nameField.ResignFirstResponder();
                lastNameField.ResignFirstResponder();
            });

            this.View.AddGestureRecognizer(screenTap);


            backButton.TouchUpInside += (sender, e) => {
                ViewModel.BackIntroduction();
            };

            nextButton.TouchUpInside += (sender, e) => {
                if (!string.IsNullOrEmpty(nameField.Text) && !string.IsNullOrEmpty(lastNameField.Text))
                {
                    ViewModel.name = nameField.Text;

                    ViewModel.last_name = lastNameField.Text;

                    ViewModel.ShowSignup2();
                }

                else
                {
                    if (string.IsNullOrEmpty(nameField.Text))
                    {
                        var okAlertController = UIAlertController.Create("Error message", "Enter name", UIAlertControllerStyle.Alert);

                        //Add Action
                        okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                        // Present Alert
                        PresentViewController(okAlertController, true, null);
                    }

                    else if (string.IsNullOrEmpty(lastNameField.Text))
                    {
                        var okAlertController = UIAlertController.Create("Error message", "Enter last name", UIAlertControllerStyle.Alert);

                        //Add Action
                        okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                        // Present Alert
                        PresentViewController(okAlertController, true, null);
                    }
                }
            };

            createEventButton.TouchUpInside += (sender, e) => {
                if (!string.IsNullOrEmpty(nameField.Text) && !string.IsNullOrEmpty(lastNameField.Text))
                {
                    ViewModel.name = nameField.Text;

                    ViewModel.last_name = lastNameField.Text;

                    ViewModel.ShowEventFirst();
                }

                else
                {
                    if (string.IsNullOrEmpty(nameField.Text))
                    {
                        var okAlertController = UIAlertController.Create("Error message", "Enter name", UIAlertControllerStyle.Alert);

                        //Add Action
                        okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                        // Present Alert
                        PresentViewController(okAlertController, true, null);
                    }

                    else if (string.IsNullOrEmpty(lastNameField.Text))
                    {
                        var okAlertController = UIAlertController.Create("Error message", "Enter last name", UIAlertControllerStyle.Alert);

                        //Add Action
                        okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                        // Present Alert
                        PresentViewController(okAlertController, true, null);
                    }
                }
            };
        }
예제 #2
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            _FirstNameField.Text    = _Acquaintance?.FirstName;
            _LastNameField.Text     = _Acquaintance?.LastName;
            _CompanyNameField.Text  = _Acquaintance?.Company;
            _JobTitleField.Text     = _Acquaintance?.JobTitle;
            _PhoneNumberField.Text  = _Acquaintance?.Phone;
            _EmailAddressField.Text = _Acquaintance?.Email;
            _StreetField.Text       = _Acquaintance?.Street;
            _CityField.Text         = _Acquaintance?.City;
            _StateField.Text        = _Acquaintance?.State;
            _ZipField.Text          = _Acquaintance?.PostalCode;

            NavigationItem.RightBarButtonItem.Clicked += async(sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(_FirstNameField.Text) || string.IsNullOrWhiteSpace(_LastNameField.Text))
                {
                    UIAlertController alert = UIAlertController.Create("Invalid name!", "A acquaintance must have both a first and last name.", UIAlertControllerStyle.Alert);

                    // cancel button
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
                }
                else if (!RequiredAddressFieldCombinationIsFilled)
                {
                    UIAlertController alert = UIAlertController.Create("Invalid address!", "You must enter either a street, city, and state combination, or a postal code.", UIAlertControllerStyle.Alert);

                    // cancel button
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
                }
                else
                {
                    if (_Acquaintance == null)
                    {
                        _Acquaintance = new Acquaintance();
                    }

                    _Acquaintance.FirstName  = _FirstNameField.Text;
                    _Acquaintance.LastName   = _LastNameField.Text;
                    _Acquaintance.Company    = _CompanyNameField.Text;
                    _Acquaintance.JobTitle   = _JobTitleField.Text;
                    _Acquaintance.Phone      = _PhoneNumberField.Text;
                    _Acquaintance.Email      = _EmailAddressField.Text;
                    _Acquaintance.Street     = _StreetField.Text;
                    _Acquaintance.City       = _CityField.Text;
                    _Acquaintance.State      = _StateField.Text;
                    _Acquaintance.PostalCode = _ZipField.Text;


                    if (_IsNew)
                    {
                        await _DataSource.AddItem(_Acquaintance);
                    }
                    else
                    {
                        await _DataSource.UpdateItem(_Acquaintance);
                    }

                    NavigationController.PopViewController(true);
                }
            };
        }
예제 #3
0
        // Function to query map image sublayers when the query button is clicked.
        private async void QuerySublayers_Click(object sender, EventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // If the population value entered is not numeric, warn the user and exit.
            double populationNumber;

            if (!double.TryParse(_populationValueInput.Text.Trim(), out populationNumber))
            {
                UIAlertController alert = UIAlertController.Create("Invalid number", "Population value must be numeric.", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);

                return;
            }

            // Get the USA map image layer (the first and only operational layer in the map).
            ArcGISMapImageLayer usaMapImageLayer = _myMapView.Map.OperationalLayers[0] as ArcGISMapImageLayer;

            // Use a utility method on the map image layer to load all the sublayers and tables.
            await usaMapImageLayer.LoadTablesAndLayersAsync();

            // Get the sublayers of interest (skip 'Highways' since it doesn't have the POP2000 field).
            ArcGISMapImageSublayer citiesSublayer   = usaMapImageLayer.Sublayers[0] as ArcGISMapImageSublayer;
            ArcGISMapImageSublayer statesSublayer   = usaMapImageLayer.Sublayers[2] as ArcGISMapImageSublayer;
            ArcGISMapImageSublayer countiesSublayer = usaMapImageLayer.Sublayers[3] as ArcGISMapImageSublayer;

            // Get the service feature table for each of the sublayers.
            ServiceFeatureTable citiesTable   = citiesSublayer.Table;
            ServiceFeatureTable statesTable   = statesSublayer.Table;
            ServiceFeatureTable countiesTable = countiesSublayer.Table;

            // Create the query parameters that will find features in the current extent with a population greater than the value entered.
            QueryParameters populationQuery = new QueryParameters
            {
                WhereClause = "POP2000 > " + _populationValueInput.Text,
                Geometry    = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry
            };

            // Query each of the sublayers with the query parameters.
            FeatureQueryResult citiesQueryResult = await citiesTable.QueryFeaturesAsync(populationQuery);

            FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

            FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

            // Display the selected cities in the graphics overlay.
            SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 16);

            foreach (Feature city in citiesQueryResult)
            {
                Graphic cityGraphic = new Graphic(city.Geometry, citySymbol);

                _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
            }

            // Display the selected counties in the graphics overlay.
            SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Cyan, 2);
            SimpleFillSymbol countySymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, System.Drawing.Color.Cyan, countyLineSymbol);

            foreach (Feature county in countiesQueryResult)
            {
                Graphic countyGraphic = new Graphic(county.Geometry, countySymbol);

                _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
            }

            // Display the selected states in the graphics overlay.
            SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.DarkCyan, 6);
            SimpleFillSymbol stateSymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, System.Drawing.Color.Cyan, stateLineSymbol);

            foreach (Feature state in statesQueryResult)
            {
                Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol);

                _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Localized texts
            String title = NSBundle.MainBundle.LocalizedString("Vernacular_P0_app_name", null).PrepareForLabel();

            lblTitle.Text      = title;
            lblTitle.TextColor = StyleSettings.TextOnDarkColor();

            lblVersion.Text      = String.Format("{0}.{1}", App.Version.Major, App.Version.Minor);
            lblVersion.TextColor = StyleSettings.ThemePrimaryColor();

            String developed = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_developed_by", null).ToUpper().PrepareForLabel();

            lblDeveloped.Text      = developed;
            lblDeveloped.TextColor = StyleSettings.ThemePrimaryColor();

            String developedWithC4rs = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_c4rs", null).PrepareForLabel();

            lblDevelopedWith.Text      = developedWithC4rs;
            lblDevelopedWith.TextColor = StyleSettings.TextOnDarkColor();

            String university = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_author", null).PrepareForLabel();

            lblUniversity.Text      = university;
            lblUniversity.TextColor = StyleSettings.TextOnDarkColor();

            String collaborators = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_contributors", null).ToUpper().PrepareForLabel();

            lblCollaborators.Text      = collaborators;
            lblCollaborators.TextColor = StyleSettings.ThemePrimaryColor();

            String collaboratorList = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_authors", null).PrepareForLabel();

            lblCollaboratorList.Text      = collaboratorList;
            lblCollaboratorList.TextColor = StyleSettings.TextOnDarkColor();

            String design = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_icon_design", null).ToUpper().PrepareForLabel();

            lblDesign.Text      = design;
            lblDesign.TextColor = StyleSettings.ThemePrimaryColor();

            String designInfo = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_icon_design_text", null).PrepareForLabel();

            lblDesignInfo.Text      = designInfo;
            lblDesignInfo.TextColor = StyleSettings.TextOnDarkColor();

            String comments = NSBundle.MainBundle.LocalizedString("Vernacular_P0_about_feedback", null).ToUpper().PrepareForLabel();

            lblComments.Text      = comments;
            lblComments.TextColor = StyleSettings.ThemePrimaryColor();

            String email = NSBundle.MainBundle.LocalizedString("Vernacular_P0_mail_address", null).PrepareForLabel();

            btnEmail.SetTitle(email, UIControlState.Normal);
            btnEmail.SetTitleColor(StyleSettings.TextOnDarkColor(), UIControlState.Normal);

            lblAppInfo.Text      = App.ApplicationInformation + ".";
            lblAppInfo.TextColor = StyleSettings.SubtleTextOnDarkColor();

            btnEmail.TouchUpInside += (object sender, EventArgs e) => {
                // Send Email
                MFMailComposeViewController mailController;

                if (MFMailComposeViewController.CanSendMail)
                {
                    Log.Debug("opening mail controller");
                    // Set mail composer
                    mailController = new MFMailComposeViewController();

                    // populate email
                    mailController.SetToRecipients(new string[] { NSBundle.MainBundle.LocalizedString("Vernacular_P0_mail_address", null) });
                    mailController.SetSubject(NSBundle.MainBundle.LocalizedString("Vernacular_P0_app_name", null));

                    // activate send button
                    mailController.Finished += (object s, MFComposeResultEventArgs args) => {
                        Console.WriteLine(args.Result.ToString());
                        args.Controller.DismissViewController(true, null);
                    };

                    // present view controller
                    this.PresentViewController(mailController, true, null);
                }
                else
                {
                    Log.Debug("failed opening mail controller");

                    String errorTitle = NSBundle.MainBundle.LocalizedString("Vernacular_P0_information_message_title_engine_error", null).PrepareForLabel();
                    String errorBody  = NSBundle.MainBundle.LocalizedString("Vernacular_P0_error_send_mail_not_configured", null).PrepareForLabel();

                    //Create Alert
                    var errorAlertController = UIAlertController.Create(errorTitle, errorBody, UIAlertControllerStyle.Alert);

                    //Add Actions
                    errorAlertController.AddAction(UIAlertAction.Create(NSBundle.MainBundle.LocalizedString("Vernacular_P0_dialog_ok", null), UIAlertActionStyle.Default, null));

                    //Present Alert
                    PresentViewController(errorAlertController, true, null);
                }
            };
        }
예제 #5
0
        private void Initialize()
        {
            try
            {
                // Define the URI for the service feature table (US state polygons).
                Uri featureTableUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

                // Create a new service feature table from the URI.
                ServiceFeatureTable censusServiceFeatureTable = new ServiceFeatureTable(featureTableUri);

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

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

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

                // Create a new simple renderer for the feature layer.
                SimpleRenderer renderer = new SimpleRenderer(fillSymbol);

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

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

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

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

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

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

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

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

                // Create and use an orbit location camera controller defined by a point and distance.
                _mySceneView.CameraController = new OrbitLocationCameraController(myMapPoint, 20000000);
            }
            catch (Exception ex)
            {
                // Something went wrong, display the error.
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
        }
예제 #6
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // 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)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // 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);

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

                // 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(string.Format("{0} : {1}", 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();
            }
        }
예제 #7
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.
//			UIImage image = UIImage.FromBundle("tvBgImage.png");
//			UIImageView iv = new UIImageView(image);
//
//
//			iv.AddConstraints(new NSLayoutConstraint[]{});
//			iv.ContentMode = UIViewContentMode.ScaleToFill;
//			View.Add(iv);
//			View.SendSubviewToBack(iv);
//

            nameField.ClearButtonMode         = UITextFieldViewMode.WhileEditing;
            serialNumberField.ClearButtonMode = UITextFieldViewMode.WhileEditing;
            valueField.ClearButtonMode        = UITextFieldViewMode.WhileEditing;

            UIColor clr = null;

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                clr = UIColor.FromRGBA(0.875f, 0.88f, 9.1f, 1f);
            }
            else
            {
                clr = UIColor.GroupTableViewBackgroundColor;
            }
            this.View.BackgroundColor = clr;

            dp      = new UIDatePicker();
            dp.Mode = UIDatePickerMode.Date;
            if (item.dateCreated.Kind == DateTimeKind.Unspecified)
            {
                item.dateCreated = DateTime.SpecifyKind(item.dateCreated, DateTimeKind.Local);
            }
            dp.Date = (NSDate)item.dateCreated;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                ac = UIAlertController.Create(
                    NSBundle.MainBundle.LocalizedString("Do you really want to change the date?", "Confirm Date Change"),
                    NSBundle.MainBundle.LocalizedString("Modifying the date of an acquired item can result in charges of insurance fraud.", "Change Warning"),
                    UIAlertControllerStyle.Alert);

                ac.AddAction(UIAlertAction.Create(NSBundle.MainBundle.LocalizedString("Cancel", "Cancel"), UIAlertActionStyle.Cancel, (alertAction) => {
                    if (dateField.IsFirstResponder)
                    {
                        dateField.ResignFirstResponder();
                    }
                }));
                ac.AddAction(UIAlertAction.Create(NSBundle.MainBundle.LocalizedString("OK", "OK"), UIAlertActionStyle.Default, (alertAction) => {
                    dateField.BecomeFirstResponder();
                }));
            }
            else
            {
                av = new UIAlertView(
                    NSBundle.MainBundle.LocalizedString("Do you really want to change the date?", "Confirm Date Change"),
                    NSBundle.MainBundle.LocalizedString("Modifying the date of an acquired item can result in charges of insurance fraud.", "Change Warning"),
                    null,
                    NSBundle.MainBundle.LocalizedString("Cancel", "Cancel"),
                    new string[] { NSBundle.MainBundle.LocalizedString("OK", "OK") });
                av.Clicked += (object sender, UIButtonEventArgs e) => {
                    Console.WriteLine("Av Clicked");
                    av.DismissWithClickedButtonIndex(e.ButtonIndex, true);
                    if (e.ButtonIndex == 0)
                    {
                        if (dateField.IsFirstResponder)
                        {
                            dateField.ResignFirstResponder();
                        }
                    }
                    else
                    {
                        dateField.BecomeFirstResponder();
                    }
                };
            }

            dateField.InputView  = dp;
            dateField.TouchDown += (sender, e) => {
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    PresentModalViewController(ac, true);
                }
                else
                {
                    av.Show();
                }
            };

            dp.ValueChanged += (object sender, EventArgs e) => {
                DateTime newDate = (DateTime)dp.Date;
                Console.WriteLine("test dp: " + newDate.ToLocalTime());
                item.dateCreated = newDate.ToLocalTime();
                dateField.Text   = item.dateCreated.ToShortDateString();
            };

            nameField.EditingChanged += (object sender, EventArgs e) => {
                this.NavigationItem.Title = nameField.Text;
            };

            takePicture.Clicked += (sender, e) => {
                if (imagePickerPopover != null && imagePickerPopover.PopoverVisible)
                {
                    // if the popover is already up, get rid of it
                    imagePickerPopover.Dismiss(true);
                    imagePickerPopover = null;
                    return;
                }

                UIImagePickerController imagePicker = new UIImagePickerController();

                // If device has camera, take picture, else pick from photo library
                if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
                {
                    imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
                }
                else
                {
                    imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
                }

                imagePicker.WeakDelegate = this;

                // Place the image picker on the screen
                //this.PresentViewController(imagePicker, true, null);
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                {
                    if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
                    {
                        this.PresentViewController(imagePicker, true, null);
                        return;
                    }
                    imagePickerPopover = new UIPopoverController(imagePicker);
                    imagePickerPopover.WeakDelegate = this;

                    // Diaplay the popover controller
                    // sender is the camera bar button item
                    imagePickerPopover.PresentFromBarButtonItem((UIBarButtonItem)sender, UIPopoverArrowDirection.Any, true);
                }
                else
                {
                    this.PresentViewController(imagePicker, true, null);
                }
            };
        }
using Foundation;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UIKit;
using CoreGraphics;

namespace SaitamaGourmet
{
	public partial class RestaurantListViewController : UIViewController
	{
		public AreaMasterMiddles targetAreaItem { get; set; }
		public List<Restaurants> restData { get; set; }
		DataSource dataSource;
		public string selectedCategory;

		public RestaurantListViewController(IntPtr handle) : base(handle)
		{
		}

		public void SetDetailItem(AreaMasterMiddles newTargetAreaItem)
		{
			if (targetAreaItem != null)
			{
				targetAreaItem = newTargetAreaItem;

				ConfigureView();
			}

		}

		void ConfigureView()
		{
			// Update the user interface for the detail item
			Title = NSBundle.MainBundle.LocalizedString("レストラン一覧", "レストラン一覧");

			restData = new List<Restaurants>();
			dataSource = new DataSource(this);

			if (IsViewLoaded && targetAreaItem != null)
			{

				// レストラン情報取得

				RestaurantSearchParam param = new RestaurantSearchParam();
				param.areacode_m = targetAreaItem.areacode_m;
				param.category_l = selectedCategory;

				GourmetNaviAPI gourmetApi = new GourmetNaviAPI();
				JObject data = gourmetApi.GetRestrantData(GourmetNaviAPI.ResturantSearch, param);

				//if (data == null && data.Count <= 2)
				//{
				//	UIAlertView alert = new UIAlertView();
				//	alert.Title = "Error";
				//	alert.AddButton("OK");
				//	alert.AddButton("Cancel");
				//	alert.Message = "This should be an error message";
				//	alert.Show();
				//}
				int i = 0;
				int count = 0;
				int perPage = 0;
				if (!IsCheckNull(data["total_hit_count"]))
				{
					count = (int)data["total_hit_count"] - 4;
				}
				if (!IsCheckNull(data["hit_per_page"]))
				{
					perPage = (int)data["hit_per_page"];
				}

				int index = 0;
				if (count > 0)
				{
					while (i < count)
					{
						if (i < count)
						{
							Restaurants rest = new Restaurants();

							try
							{
								if (!IsCheckNull(data["rest"][index]["name"]))
								{
									rest.name = (string)data["rest"][index]["name"];
								}

								if (!IsCheckNull(data["rest"][index]["name_sub"]))
								{
									rest.name_sub = (string)data["rest"][index]["name_sub"];
								}

								if (!IsCheckNull(data["rest"][index]["name_kana"]))
								{
									rest.name_kana = (string)data["rest"][index]["name_kana"];
								}

								if (!IsCheckNull(data["rest"][index]["business_hour"]))
								{
									rest.business_hour = (string)data["rest"][index]["business_hour"];
								}

								if (!IsCheckNull(data["rest"][index]["opentime"]))
								{
									rest.opentime = data["rest"][index]["opentime"].ToString();
								}

								if (!IsCheckNull(data["rest"][index]["holiday"]))
								{
									rest.holiday = (string)data["rest"][index]["holiday"];
								}

								if (!IsCheckNull(data["rest"][index]["address"]))
								{
									rest.address = (string)data["rest"][index]["address"];
								}

								if (!IsCheckNull(data["rest"][index]["tel"]))
								{
									rest.tel = (string)data["rest"][index]["tel"];
								}

								if (!IsCheckNull(data["rest"][index]["fax"]))
								{
									rest.fax = (string)data["rest"][index]["fax"];
								}

								if (!IsCheckNull(data["rest"][index]["pr"]["pr_short"]))
								{
									rest.pr_short = (string)data["rest"][index]["pr"]["pr_short"];
								}

								if (!IsCheckNull(data["rest"][index]["pr"]["pr_long"]))
								{
									rest.pr_long = (string)data["rest"][index]["pr"]["pr_long"];
								}

								if (!IsCheckNull(data["rest"][index]["access"]["line"]))
								{
									rest.line = (string)data["rest"][index]["access"]["line"];
								}

								if (!IsCheckNull(data["rest"][index]["access"]["station"]))
								{
									rest.station = (string)data["rest"][index]["access"]["station"];
								}

								if (!IsCheckNull(data["rest"][index]["access"]["station_exit"]))
								{
									rest.station_exit = (string)data["rest"][index]["access"]["station_exit"];
								}

								if (!IsCheckNull(data["rest"][index]["access"]["walk"]))
								{
									rest.walk = (string)data["rest"][index]["access"]["walk"];
								}

								if (!IsCheckNull(data["rest"][index]["access"]["note"]))
								{
									rest.note = (string)data["rest"][index]["access"]["note"];
								}

								if (!IsCheckNull(data["rest"][index]["budget"]))
								{
									rest.budget = (string)data["rest"][index]["budget"];
								}

								if (!IsCheckNull(data["rest"][index]["image_url"]["shop_image1"]))
								{
									rest.shop_image1 = (string)data["rest"][index]["image_url"]["shop_image1"];
								}

								if (!IsCheckNull(data["rest"][index]["image_url"]["shop_image2"]))
								{
									rest.shop_image2 = (string)data["rest"][index]["image_url"]["shop_image2"];
								}

								if (!IsCheckNull(data["rest"][index]["image_url"]["qrcode"]))
								{
									rest.qrcode = (string)data["rest"][index]["image_url"]["qrcode"];
								}

								if (!IsCheckNull(data["rest"][index]["url_mobile"]))
								{
									rest.url_mobile = (string)data["rest"][index]["url_mobile"];
								}

								if (!IsCheckNull(data["rest"][index]["url"]))
								{
									rest.url = (string)data["rest"][index]["url"];
								}

								if (!IsCheckNull(data["rest"][index]["credit_card"]))
								{
									rest.credit_card = (string)data["rest"][index]["credit_card"];
								}

								if (!IsCheckNull(data["rest"][index]["latitude"]))
								{
									rest.latitude = (double)data["rest"][index]["latitude"];
								}

								if (!IsCheckNull(data["rest"][index]["longitude"]))
								{
									rest.longitude = (double)data["rest"][index]["longitude"];
								}
								//rest.latitude_wgs84 = (double)data["rest"][index]["latitude_wgs84"];
								//rest.longitude_wgs84 = (double)data["rest"][index]["ongitude_wgs84"];

							}
							catch (Exception e)
							{
								Console.WriteLine(e.ToString());
								break;
							}
							index++;
							restData.Add(rest);
							dataSource.Objects.Add(rest);
						}

						i++;

						if ((i % perPage) == 0)
						{
							param.offset_page++;
							index = 0;
							try
							{
								data = gourmetApi.GetRestrantData(GourmetNaviAPI.ResturantSearch, param);
							}
							catch (Exception e)
							{
								Console.WriteLine(e.ToString());
								break;
							};
						}
					}

					RestaurantListTableView.Source = dataSource;
					((RestaurantTabViewController)(this.ParentViewController)).SetRestData(restData);
				}
				else {
					var alert = UIAlertController.Create("メッセージ", "指定され店舗の情報が存在しません。", UIAlertControllerStyle.Alert);
					alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, action =>
					{

						NavigationController.PopViewController(true);

					}));
					this.PresentViewController(alert, true, null);
				}
			}
		}

		private bool IsCheckNull(object o)
		{
			if (o == null || o.ToString() == "{}")
			{
				return true;
			}
			else {
				return false;
			}
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			// Perform any additional setup after loading the view, typically from a nib.
			targetAreaItem = ((RestaurantTabViewController)(this.ParentViewController)).targetAreaItem;
			selectedCategory = ((RestaurantTabViewController)(this.ParentViewController)).selectedCategory;

			ConfigureView();
		}

		public override void ViewWillAppear(bool animated)
		{
			base.ViewWillAppear(animated);
		}

		public override void ViewWillDisappear(bool animated)
		{
			base.ViewWillDisappear(animated);
			((RestaurantTabViewController)(this.ParentViewController)).SetRestData(restData);
		}

		public override void DidReceiveMemoryWarning()
		{
			base.DidReceiveMemoryWarning();
		}

		public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
		{
			if (segue.Identifier == "restDetailFromList")
			{
				var indexPath = RestaurantListTableView.IndexPathForSelectedRow;
				var item = dataSource.Objects[indexPath.Row];

				((RestDetailTabViewController)segue.DestinationViewController).SetDetailItem(item);
			}
		}

		static UIImage FromUrl(string uri)
		{
			using (var url = new NSUrl(uri))
			using (var data = NSData.FromUrl(url))
				return UIImage.LoadFromData(data);
		}

		class DataSource : UITableViewSource
		{
			NSString CellIdentifier = new NSString("Cell");
			readonly List<Restaurants> objects = new List<Restaurants>();
			readonly RestaurantListViewController controller;

			public DataSource(RestaurantListViewController controller)
			{
				this.controller = controller;
			}

			public IList<Restaurants> Objects
			{
				get { return objects; }
			}

			// Customize the number of sections in the table view.
			public override nint NumberOfSections(UITableView tableView)
			{
				return 1;
			}

			public override nint RowsInSection(UITableView tableview, nint section)
			{
				return objects.Count;
			}

		
			private int rowNumber { get; set; }
			public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
			{
				return 80;
			}

			public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
			{

				controller.PerformSegue("restDetailFromList", this);

			}
			public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
			{
				// Return false if you do not want the specified item to be editable.
				return true;
			}

			//Customize the appearance of table view cells.
			public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
			{

				var cell = tableView.DequeueReusableCell(CellIdentifier) as CustomVegeCell;
				if (cell == null)
				{
					cell = new CustomVegeCell(CellIdentifier);
				}
				if (String.IsNullOrWhiteSpace(objects[indexPath.Row].shop_image1))
				{
					cell.UpdateCell(objects[indexPath.Row].name
					  , UIImage.FromFile("noImage2.png")
					  , objects[indexPath.Row].address, objects[indexPath.Row].station, objects[indexPath.Row].budget);
				}
				else {
					cell.UpdateCell(objects[indexPath.Row].name
					  , FromUrl(objects[indexPath.Row].shop_image1)
					  , objects[indexPath.Row].address, objects[indexPath.Row].station, objects[indexPath.Row].budget);
				}
				cell.BackgroundColor = UIColor.Clear;



				return cell;


			}

		}
	}


	// Custom Cell

	public class CustomVegeCell : UITableViewCell
	{
		UILabel headingLabel;
		UILabel subheadingLabel;
		UILabel subheadingLabel1;
		UILabel subheadingLabel2;

		UIImageView imageView;


		public CustomVegeCell(NSString Cell) : base(UITableViewCellStyle.Default, Cell)

		{
			imageView = new UIImageView();
			headingLabel = new UILabel()
			{
				Font = UIFont.FromName("Cochin-BoldItalic", 17f),
				TextColor = UIColor.FromRGB(127, 51, 0),
				//BackgroundColor = UIColor.Clear
			} ;
			subheadingLabel = new UILabel()
			{
				Font = UIFont.FromName("AmericanTypewriter", 12f),
				TextColor = UIColor.FromRGB(80, 80, 80),
				//TextAlignment = UITextAlignment.Center,
				BackgroundColor = UIColor.Clear
			} ;

			subheadingLabel1 = new UILabel()
			{
				Font = UIFont.FromName("AmericanTypewriter", 11f),
				TextColor = UIColor.FromRGB(10, 10, 10),
			} ;

			subheadingLabel2 = new UILabel()
			{
				Font = UIFont.FromName("AmericanTypewriter", 12f),
				TextColor = UIColor.Red,
			} ;

			headingLabel.Lines = 0;
			headingLabel.LineBreakMode = UILineBreakMode.CharacterWrap;
			headingLabel.SizeToFit();

			subheadingLabel.Lines = 0;
			subheadingLabel.LineBreakMode = UILineBreakMode.CharacterWrap;
			subheadingLabel.SizeToFit();

			subheadingLabel1.Lines = 0;
			subheadingLabel1.LineBreakMode = UILineBreakMode.CharacterWrap;
			subheadingLabel1.SizeToFit();

			ContentView.AddSubviews(new UIView[] { imageView, headingLabel, subheadingLabel, subheadingLabel1, subheadingLabel2 });

		}

		public void UpdateCell(string caption, UIImage image, string subtitle, string subtitle1, string subtitle2)
		{

			headingLabel.Text = caption;
			imageView.Image = image;
			subheadingLabel.Text = subtitle;
			subheadingLabel1.Text = "最寄駅:" + subtitle1;
			subheadingLabel2.Text = "予算:" + subtitle2 + "円~";


		}

		public override void LayoutSubviews()
		{
			base.LayoutSubviews();
			imageView.Frame = new CGRect(3, 2, 70, ContentView.Bounds.Height - 3);
			headingLabel.Frame = new CGRect(ContentView.Bounds.Width - 300, -2, 300, 40);
			subheadingLabel.Frame = new CGRect(ContentView.Bounds.Width - 300, 30, 300, 35);
			subheadingLabel1.Frame = new CGRect(ContentView.Bounds.Width - 135, 45, 300, 50);
			subheadingLabel2.Frame = new CGRect(ContentView.Bounds.Width - 300, 45, 300, 50);
		}
	}
}

예제 #9
0
        public void Initialise()
        {
            Switch.ValueChanged += delegate {
                file.Priority = Switch.On ? Priority.Highest : Priority.DoNotDownload;

                if (manager != null)
                {
                    Manager.Singletone.UpdateMasterController(manager);
                }
            };

            if (Share != null)
            {
                Share.TouchUpInside += delegate {
                    var alert = UIAlertController.Create(file.Path, null, UIAlertControllerStyle.ActionSheet);
                    var share = UIAlertAction.Create("Share", UIAlertActionStyle.Default, delegate {
                        NSObject[] mass     = { null, new NSUrl(file.FullPath, false) };
                        var shareController = new UIActivityViewController(mass, null);

                        if (shareController.PopoverPresentationController != null)
                        {
                            shareController.PopoverPresentationController.SourceView = Share;
                            shareController.PopoverPresentationController.SourceRect = Share.Bounds;
                            shareController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any;
                        }

                        NSString[] set = { UIActivityType.PostToWeibo };
                        shareController.ExcludedActivityTypes = set;

                        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(shareController, true, null);
                    });
                    var delete = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate {
                        var deleteController = UIAlertController.Create("Are you sure to delete?", file.Path, UIAlertControllerStyle.ActionSheet);

                        var deleteAction = UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate {
                            if (manager.State == TorrentState.Stopped)
                            {
                                file.fileRemoved = true;
                                Switch.SetState(false, true);
                                file.Priority = Priority.DoNotDownload;
                                UpdateInDetail();
                                if (File.Exists(file.FullPath))
                                {
                                    File.Delete(file.FullPath);
                                }
                            }
                            else
                            {
                                var alertController = UIAlertController.Create("Error deleting file", "File cannot be removed while the download is in progress.\nStop the downloading first!", UIAlertControllerStyle.Alert);
                                var ok = UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null);
                                alertController.AddAction(ok);
                                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alertController, true, null);
                            }
                        });
                        var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null);

                        deleteController.AddAction(deleteAction);
                        deleteController.AddAction(cancelAction);

                        if (deleteController.PopoverPresentationController != null)
                        {
                            deleteController.PopoverPresentationController.SourceView = Share;
                            deleteController.PopoverPresentationController.SourceRect = Share.Bounds;
                            deleteController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any;
                        }

                        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(deleteController, true, null);
                    });
                    var cancel = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null);

                    alert.AddAction(share);
                    alert.AddAction(delete);
                    alert.AddAction(cancel);

                    if (alert.PopoverPresentationController != null)
                    {
                        alert.PopoverPresentationController.SourceView = Share;
                        alert.PopoverPresentationController.SourceRect = Share.Bounds;
                        alert.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Right;
                    }

                    UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
                };
            }
        }
예제 #10
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            CachedImageRenderer.Init();             // Initializing FFImageLoading
            AnimationViewRenderer.Init();           // Initializing Lottie

            UXDivers.Artina.Shared.GrialKit.Init(new ThemeColors(), "RoboScout.iOS.GrialLicense");

#if !DEBUG
            // Reminder to update the project license to production mode before publishing
            if (!UXDivers.Artina.Shared.License.IsProductionLicense())
            {
                BeginInvokeOnMainThread(() =>
                {
                    try
                    {
                        var alert = UIAlertController.Create(
                            "Grial UI Kit Reminder",
                            "Before publishing this App remember to change the license file to PRODUCTION MODE so it doesn't expire.",
                            UIAlertControllerStyle.Alert);

                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));

                        var root       = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        var controller = root.PresentedViewController ?? root.PresentationController.PresentedViewController;
                        controller.PresentViewController(alert, animated: true, completionHandler: null);
                    }
                    catch
                    {
                    }
                });
            }
#endif

            // Code for starting up the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
#endif

            FormsHelper.ForceLoadingAssemblyContainingType(typeof(UXDivers.Effects.Effects));
            FormsHelper.ForceLoadingAssemblyContainingType <UXDivers.Effects.iOS.CircleEffect>();
            FormsHelper.ForceLoadingAssemblyContainingType <TabItem>();
            FormsHelper.ForceLoadingAssemblyContainingType <Repeater>();
            FormsHelper.ForceLoadingAssemblyContainingType <FFImageLoading.Transformations.BlurredTransformation>();

            ReferenceCalendars();

#if GORILLA
            LoadApplication(
                UXDivers.Gorilla.iOS.Player.CreateApplication(
                    new UXDivers.Gorilla.Config("Good Gorilla")
                    // Shared.Base
                    .RegisterAssemblyFromType <UXDivers.Artina.Shared.NegateBooleanConverter>()
                    // Shared
                    .RegisterAssemblyFromType <UXDivers.Artina.Shared.CircleImage>()
                    // Tab Control
                    .RegisterAssembly(GorillaSdkHelper.TabControlType.Assembly)
                    // Repeater Control
                    .RegisterAssembly(GorillaSdkHelper.RepeaterControlType.Assembly)

                    // Effects
                    .RegisterAssembly(typeof(UXDivers.Effects.Effects).Assembly)

                    // // FFImageLoading.Transformations
                    .RegisterAssemblyFromType <FFImageLoading.Transformations.BlurredTransformation>()
                    // FFImageLoading.Forms
                    .RegisterAssemblyFromType <FFImageLoading.Forms.CachedImage>()

                    // Grial Application PCL
                    .RegisterAssembly(typeof(RoboScout.App).Assembly)

                    .RegisterAssembly(typeof(Lottie.Forms.AnimationView).Assembly)
                    ));
#else
            LoadApplication(new App());
#endif

            return(base.FinishedLaunching(app, options));
        }
예제 #11
0
 public override IDisposable Alert(AlertConfig config) => this.Present(() =>
 {
     var alert = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert);
     alert.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x => config.OnAction?.Invoke()));
     return(alert);
 });
예제 #12
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            string nameChanged  = string.Empty;
            string emailChanged = string.Empty;

            NameField.ClearsOnBeginEditing  = true;
            EmailField.ClearsOnBeginEditing = true;

            NameField.EditingChanged += (sernder2, e2) =>
            {
                nameChanged = ((UITextField)sernder2).Text;
                //NameFamTextField.ResignFirstResponder();
            };
            EmailField.EditingChanged += (s, e) =>
            {
                emailChanged = ((UITextField)s).Text;
                //EmailTextField.ResignFirstResponder();
            };

            AddToListButton.TouchUpInside += (sender, e) => {
                NameField.ResignFirstResponder();
                EmailField.ResignFirstResponder();
                if (String.IsNullOrEmpty(nameChanged))
                {
                    var alert = UIAlertController.Create("Empty Family's Member Name", "Please Enter Name", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                if (String.IsNullOrEmpty(emailChanged))
                {
                    var alert = UIAlertController.Create("Empty Email", "Please Enter Email adress", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                else
                {
                    FamilyMemberController familyMemberController = this.Storyboard.InstantiateViewController("FamilyMemberController") as FamilyMemberController;
                    if (familyMemberController != null)
                    {
                        try
                        {
                            Family.Add(new FamilyMember(nameChanged, emailChanged));
                            AzureHelper.AddNewMember(nameChanged, emailChanged);
                            var alert = UIAlertController.Create("Successful", "New family member added", UIAlertControllerStyle.Alert);
                            alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                            PresentViewController(alert, true, null);
                        }
                        catch
                        {
                            var alert = UIAlertController.Create("Failed", "Failed to add new member", UIAlertControllerStyle.Alert);
                            alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                            PresentViewController(alert, true, null);
                        }
                    }
                }
            };

            RemoveButton.TouchUpInside += (sender, e) =>
            {
                NameField.ResignFirstResponder();
                EmailField.ResignFirstResponder();
                if (String.IsNullOrEmpty(nameChanged))
                {
                    var alert = UIAlertController.Create("Empty Family's Member Name", "Please Enter Name", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                else
                {
                    try
                    {
                        AzureHelper.RemoveFamilyMember(nameChanged);
                        var alert = UIAlertController.Create("Successful", nameChanged + " was removed from family list", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                        PresentViewController(alert, true, null);
                    }
                    catch
                    {
                        var alert = UIAlertController.Create("Failed", "Failed to remove member", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                        PresentViewController(alert, true, null);
                    }
                }
            };
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            activityView                  = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
            activityView.Frame            = View.Frame;
            activityView.BackgroundColor  = UIColor.FromRGBA(0, 0, 0, 0.6f);
            activityView.Center           = View.Center;
            activityView.HidesWhenStopped = true;
            View.AddSubview(activityView);

            tlc = TimeLoggingController.GetInstance();

            if (timeLogEntry == null)
            {
                throw new ArgumentException("timeLogEntry is null.");
            }

            if (isAddingMode)
            {
                barBtnItem = new UIBarButtonItem(UIBarButtonSystemItem.Save, async(s, e) =>
                {
                    activityView.StartAnimating();
                    try
                    {
                        await PDashAPI.Controller.AddATimeLog(timeLogEntry.Comment, timeLogEntry.StartDate, timeLogEntry.Task.Id, timeLogEntry.LoggedTime, timeLogEntry.InterruptTime, false);
                        activityView.StopAnimating();
                        NavigationController.PopViewController(true);
                    }
                    catch (Exception ex)
                    {
                        activityView.StopAnimating();
                        ViewControllerHelper.ShowAlert(this, "Add Time Log", ex.Message + " Please try again later.");
                    }
                });
            }
            else
            {
                barBtnItem = new UIBarButtonItem(UIBarButtonSystemItem.Trash, (s, e) =>
                {
                    UIAlertController actionSheetAlert = UIAlertController.Create(null, "This time log will be deleted", UIAlertControllerStyle.ActionSheet);

                    actionSheetAlert.AddAction(UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, async(action) =>
                    {
                        if (isActiveTimeLog())
                        {
                            ViewControllerHelper.ShowAlert(this, "Oops", "You are currently logging time to this time log. Please stop the timmer first.");
                        }
                        else
                        {
                            activityView.StartAnimating();
                            try
                            {
                                await PDashAPI.Controller.DeleteTimeLog(timeLogEntry.Id.ToString());
                                activityView.StopAnimating();
                                NavigationController.PopViewController(true);
                            }
                            catch (Exception ex)
                            {
                                activityView.StopAnimating();
                                ViewControllerHelper.ShowAlert(this, "Delete Time Log", ex.Message + " Please try again later.");
                            }
                        }
                    }));

                    actionSheetAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => Console.WriteLine("Cancel button pressed.")));

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

                    // Display the alertg
                    this.PresentViewController(actionSheetAlert, true, null);
                });
            }

            NavigationItem.RightBarButtonItem = barBtnItem;

            ProjectNameLabel.Text = timeLogEntry.Task.Project.Name;
            TaskNameLabel.Text    = timeLogEntry.Task.FullName;
            StartTimeText.Text    = Util.GetInstance().GetLocalTime(timeLogEntry.StartDate).ToString("g");

            // set up start time customized UIpicker

            StartTimePicker = new UIDatePicker(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 250, this.View.Frame.Width - 20, 200f));
            StartTimePicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            StartTimePicker.UserInteractionEnabled = true;
            StartTimePicker.Mode        = UIDatePickerMode.DateAndTime;
            StartTimePicker.MaximumDate = ViewControllerHelper.DateTimeUtcToNSDate(DateTime.UtcNow);

            startTimeSelectedDate = Util.GetInstance().GetServerTime(timeLogEntry.StartDate);

            StartTimePicker.ValueChanged += (Object sender, EventArgs e) =>
            {
                startTimeSelectedDate = ViewControllerHelper.NSDateToDateTimeUtc((sender as UIDatePicker).Date);
            };

            StartTimePicker.BackgroundColor = UIColor.White;
            StartTimePicker.SetDate(ViewControllerHelper.DateTimeUtcToNSDate(Util.GetInstance().GetServerTime(timeLogEntry.StartDate)), true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            // Create a 'done' button for the toolbar and add it to the toolbar

            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.StartTimeText.Text = Util.GetInstance().GetLocalTime(startTimeSelectedDate).ToString();
                timeLogEntry.StartDate  = startTimeSelectedDate;
                this.StartTimeText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    try
                    {
                        await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, timeLogEntry.StartDate, timeLogEntry.Task.Id, null, null, false);
                    }
                    catch (Exception ex)
                    {
                        ViewControllerHelper.ShowAlert(this, "Change Start Time", ex.Message + " Please try again later.");
                    }
                }
            };

            var spacer = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace)
            {
                Width = 50
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.StartTimeText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.StartTimeText.InputView          = StartTimePicker;
            this.StartTimeText.InputAccessoryView = toolbar;

            DeltaText.Text = TimeSpan.FromMinutes(timeLogEntry.LoggedTime).ToString(@"hh\:mm");

            IntText.Text = TimeSpan.FromMinutes(timeLogEntry.InterruptTime).ToString(@"hh\:mm");

            CommentText.SetTitle(timeLogEntry.Comment ?? "No Comment", UIControlState.Normal);

            CommentText.TouchUpInside += (sender, e) =>
            {
                UIAlertView alert = new UIAlertView();
                alert.Title = "Comment";
                alert.AddButton("Cancel");
                alert.AddButton("Save");
                alert.Message        = "Please enter new Comment";
                alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
                UITextField textField = alert.GetTextField(0);
                textField.Placeholder = timeLogEntry.Comment ?? "No Comment";
                alert.Clicked        += CommentButtonClicked;
                alert.Show();
            };

            /////Delta Picker
            DeltaPicker = new UIPickerView(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 250, this.View.Frame.Width - 20, 200f));
            DeltaPicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            DeltaPicker.UserInteractionEnabled = true;
            DeltaPicker.ShowSelectionIndicator = true;

            string[] hours   = new string[24];
            string[] minutes = new string[60];

            for (int i = 0; i < hours.Length; i++)
            {
                hours[i] = i.ToString();
            }
            for (int i = 0; i < minutes.Length; i++)
            {
                minutes[i] = i.ToString("00");
            }

            StatusPickerViewModel deltaModel = new StatusPickerViewModel(hours, minutes);

            int h = (int)timeLogEntry.LoggedTime / 60;
            int m = (int)timeLogEntry.LoggedTime % 60;

            this.deltaSelectedHour   = h.ToString();
            this.deltaSelectedMinute = m.ToString("00");

            deltaModel.NumberSelected += (Object sender, EventArgs e) =>
            {
                this.deltaSelectedHour   = deltaModel.selectedHour;
                this.deltaSelectedMinute = deltaModel.selectedMinute;
            };

            DeltaPicker.Model           = deltaModel;
            DeltaPicker.BackgroundColor = UIColor.White;
            DeltaPicker.Select(h, 0, true);
            DeltaPicker.Select(m, 1, true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            // Create a 'done' button for the toolbar and add it to the toolbar
            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.DeltaText.Text = this.deltaSelectedHour + ":" + this.deltaSelectedMinute;
                double oldLoggedTime = timeLogEntry.LoggedTime;
                timeLogEntry.LoggedTime = int.Parse(this.deltaSelectedHour) * 60 + int.Parse(this.deltaSelectedMinute);
                this.DeltaText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    if (isActiveTimeLog())
                    {
                        tlc.SetLoggedTime((int)timeLogEntry.LoggedTime);
                    }
                    else
                    {
                        try
                        {
                            await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, null, timeLogEntry.Task.Id, timeLogEntry.LoggedTime - oldLoggedTime, null, false);
                        }
                        catch (Exception ex)
                        {
                            ViewControllerHelper.ShowAlert(this, "Change Logged Time", ex.Message + " Please try again later.");
                        }
                    }
                }
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.DeltaText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.DeltaText.InputView          = DeltaPicker;
            this.DeltaText.InputAccessoryView = toolbar;

            ////// Int Picker
            IntPicker = new UIPickerView(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 200, this.View.Frame.Width - 20, 200f));
            IntPicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            IntPicker.UserInteractionEnabled = true;
            IntPicker.ShowSelectionIndicator = true;
            IntPicker.BackgroundColor        = UIColor.White;

            IntPicker.Select(0, 0, true);

            StatusPickerViewModel intModel = new StatusPickerViewModel(hours, minutes);

            intModel.NumberSelected += (Object sender, EventArgs e) =>
            {
                this.intSelectedHour   = intModel.selectedHour;
                this.intSelectedMinute = intModel.selectedMinute;
            };

            IntPicker.Model = intModel;

            IntPicker.Select((int)timeLogEntry.InterruptTime / 60, 0, true);
            IntPicker.Select((int)timeLogEntry.InterruptTime % 60, 1, true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.IntText.Text          = this.intSelectedHour + ":" + this.intSelectedMinute;
                timeLogEntry.InterruptTime = int.Parse(this.intSelectedHour) * 60 + int.Parse(this.intSelectedMinute);
                this.IntText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    if (isActiveTimeLog())
                    {
                        tlc.SetInterruptTime((int)timeLogEntry.InterruptTime);
                    }
                    else
                    {
                        try
                        {
                            await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, null, timeLogEntry.Task.Id, null, timeLogEntry.InterruptTime, false);
                        }
                        catch (Exception ex)
                        {
                            ViewControllerHelper.ShowAlert(this, "Change Interrupt Time", ex.Message + " Please try again later.");
                        }
                    }
                }
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.IntText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.IntText.InputView          = IntPicker;
            this.IntText.InputAccessoryView = toolbar;
        }
예제 #14
0
 void ShowAlert(string message, double seconds)
 {
     alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) => { dismissMessage(); });
     alert      = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
     UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
 }
예제 #15
0
        //sharing options
        private void shareAlert(string title, string message)
        {
            UIAlertController shareController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);


            //facebook servers
            UIAlertAction facebookAction = UIAlertAction.Create("Facebook", UIAlertActionStyle.Default, (Action) => {
                NSUrl facebookURL = NSUrl.FromString("");

                if (UIApplication.SharedApplication.CanOpenUrl(facebookURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(facebookURL);
                    shareController.Dispose();
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(facebookURL) == false)
                {
                    AI.AIEnglish("Cannot connect you to the facebook servers. Check your internet connection", "en-US", 2.0f, 1.0f, 1.0f);
                    shareController.Dispose();
                }
            });

            //twitter servers
            UIAlertAction twitterAction = UIAlertAction.Create("Twitter", UIAlertActionStyle.Default, (Action) =>
            {
                NSUrl twitterURL = NSUrl.FromString("");

                if (UIApplication.SharedApplication.CanOpenUrl(twitterURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(twitterURL);
                    shareController.Dispose();
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(twitterURL) == false)
                {
                    AI.AIEnglish("Cannot connect you to the twitter servers. Check your internet connection", "en-US", 2.0f, 1.0f, 1.0f);
                    shareController.Dispose();
                }
            });

            //email a friend option
            UIAlertAction emailFriend = UIAlertAction.Create("\ud83d\udc8c Email a Friend", UIAlertActionStyle.Default, (Action) =>
            {
                MFMailComposeViewController mailEmail = new MessageUI.MFMailComposeViewController();

                if (MFMailComposeViewController.CanSendMail == true)
                {
                    this.PresentViewController(mailEmail, true, null);
                }

                else
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("Error cannot open mail box. Check if the mail box is enabled on your iPad", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("Error cannot open mail box. Check if the mail box is enabled on your iPhone", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                }

                mailEmail.Finished += (sender, e) =>
                {
                    //mail closes
                    mailEmail.DismissViewController(true, null);
                };
            });

            //text a friend option
            UIAlertAction textFriend = UIAlertAction.Create("\ud83d\udcf2 Text a friend", UIAlertActionStyle.Default, (Action) => {
                NSUrl textFriendURL = NSUrl.FromString("sms:");

                if (UIApplication.SharedApplication.CanOpenUrl(textFriendURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(textFriendURL);
                }
                else if (UIApplication.SharedApplication.CanOpenUrl(textFriendURL) == false)
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("Error cannot open text message box. Check if the text messages are enabled on your iPad", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("Error cannot open text message box. Check if the text messages are enabled on your iPhone", "en-US", 2.0f, 1.0f, 1.0f);
                    }
                }
            });

            UIAlertAction rateOnAppStore = UIAlertAction.Create("\ud83d\udc4d Rate on App Store", UIAlertActionStyle.Default, (Action) =>
            {
                NSUrl urlRateAppURL = NSUrl.FromString("");                 //url of application on app store

                if (UIApplication.SharedApplication.CanOpenUrl(urlRateAppURL) == true)
                {
                    UIApplication.SharedApplication.OpenUrl(urlRateAppURL);
                }

                else
                {
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                    {
                        AI.AIEnglish("No internet connection detected. Cannot connect to the App Store", "en-US", 2.5f, 1.0f, 1.0f);
                    }
                    else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        AI.AIEnglish("No internet connection detected.  Cannot connect to the App Store", "en-US", 2.5f, 1.0f, 1.0f);
                    }
                    shareController.Dispose();
                }
            });

            UIAlertAction denied = UIAlertAction.Create("Maybe Later", UIAlertActionStyle.Destructive, (Action) =>
            {
                shareController.Dispose();
            });

            shareController.AddAction(facebookAction);
            shareController.AddAction(twitterAction);
            shareController.AddAction(emailFriend);
            shareController.AddAction(textFriend);
            shareController.AddAction(rateOnAppStore);
            shareController.AddAction(denied);

            if (this.PresentedViewController == null)
            {
                this.PresentViewController(shareController, true, null);
            }

            else if (this.PresentedViewController != null)
            {
                this.PresentedViewController.DismissViewController(true, () =>
                {
                    this.PresentedViewController.Dispose();
                    this.PresentViewController(shareController, true, null);
                });
            }
        }
예제 #16
0
        private async void OnRunAnalysisClicked(object sender, EventArgs e)
        {
            // Clear any existing results.
            _myMapView.Map.OperationalLayers.Clear();

            // Show the animating progress bar .
            _progressBar.StartAnimating();

            // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis.
            DateTime fromDate = (DateTime)_selectionView.StartPicker.Date;
            DateTime toDate   = (DateTime)_selectionView.EndPicker.Date;

            // The end date must be at least one day after the start date.
            if (toDate <= fromDate.AddDays(1))
            {
                // Show error message.
                UIAlertController alert = UIAlertController.Create("Invalid date range",
                                                                   "Please enter a valid date range. There has to be at least one day in between To and From dates.", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);

                // Stop the progress bar from animating (which also hides it as well).
                _progressBar.StopAnimating();

                return;
            }

            // Create the parameters that are passed to the used geoprocessing task.
            GeoprocessingParameters hotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);

            // Construct the date query.
            string myQueryString = $"(\"DATE\" > date '{fromDate:yyyy-MM-dd 00:00:00}' AND \"DATE\" < date '{toDate:yyy-MM-dd 00:00:00}')";

            // Add the query that contains the date range used in the analysis.
            hotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString));

            // Create job that handles the communication between the application and the geoprocessing task.
            _hotspotJob = _hotspotTask.CreateJob(hotspotParameters);
            try
            {
                // Execute the geoprocessing analysis and wait for the results.
                GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync();

                // Add results to a map using map server from a geoprocessing task.
                // Load to get access to full extent.
                await analysisResult.MapImageLayer.LoadAsync();

                // Add the analysis layer to the map view.
                _myMapView.Map.OperationalLayers.Add(analysisResult.MapImageLayer);

                // Zoom to the results.
                await _myMapView.SetViewpointAsync(new Viewpoint(analysisResult.MapImageLayer.FullExtent));
            }
            catch (TaskCanceledException)
            {
                // This is thrown if the task is canceled. Ignore.
            }
            catch (Exception ex)
            {
                // Display error messages if the geoprocessing task fails.
                if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null)
                {
                    // Report error.
                    UIAlertController alert = UIAlertController.Create("Geoprocessing Error", _hotspotJob.Error.Message, UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                else
                {
                    // Report error.
                    UIAlertController alert = UIAlertController.Create("Sample error", ex.ToString(), UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            }
            finally
            {
                // Stop the progress bar from animating (which also hides it).
                _progressBar.StopAnimating();
            }
        }
예제 #17
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            RefreshProfileTimer           = new System.Timers.Timer();
            RefreshProfileTimer.AutoReset = true;
            RefreshProfileTimer.Interval  = 300 * 1000; // every 5 minutes
            RefreshProfileTimer.Elapsed  += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                Rock.Mobile.Threading.Util.PerformOnUIThread(
                    delegate
                {
                    RefreshProfile( );
                });
            };

            // setup the fake header
            HeaderView = new UIView( );
            View.AddSubview(HeaderView);

            HeaderView.BackgroundColor = Rock.Mobile.UI.Util.GetUIColor(ControlStylingConfig.BackgroundColor);

            // set the title image for the bar if there's no safe area defined. (A safe area is like, say, the notch for iPhone X)
            nfloat safeAreaTopInset = 0;

            // Make sure they're on iOS 11 before checking for insets. This is only needed for iPhone X anyways, which shipped with iOS 11.
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                safeAreaTopInset = UIApplication.SharedApplication.KeyWindow.SafeAreaInsets.Top;
            }

            if (safeAreaTopInset == 0)
            {
                string imagePath = NSBundle.MainBundle.BundlePath + "/" + PrivatePrimaryNavBarConfig.LogoFile_iOS;
                LogoView = new UIImageView(new UIImage(imagePath));
                LogoView.SizeToFit( );
                LogoView.Layer.AnchorPoint = CGPoint.Empty;
                HeaderView.AddSubview(LogoView);
            }

            ScrollView = new UIScrollViewWrapper();

            View.AddSubview(ScrollView);
            ScrollView.Parent = this;

            BlockerView = new UIBlockerView(ScrollView, View.Bounds.ToRectF( ));

            //setup styles
            View.BackgroundColor = Rock.Mobile.UI.Util.GetUIColor(ControlStylingConfig.BackgroundColor);

            NickName = new StyledTextField();
            ScrollView.AddSubview(NickName.Background);

            ControlStyling.StyleTextField(NickName.Field, ProfileStrings.NickNamePlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(NickName.Background);
            NickName.Field.AutocapitalizationType = UITextAutocapitalizationType.Words;
            NickName.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            NickName.Field.EditingDidBegin       += (sender, e) => { Dirty = true; };

            LastName = new StyledTextField();

            LastName.Field.AutocapitalizationType = UITextAutocapitalizationType.Words;
            LastName.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(LastName.Field, ProfileStrings.LastNamePlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(LastName.Background);
            LastName.Field.EditingDidBegin += (sender, e) => { Dirty = true; };

            Email = new StyledTextField();
            ScrollView.AddSubview(Email.Background);
            Email.Field.AutocapitalizationType = UITextAutocapitalizationType.None;
            Email.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ScrollView.AddSubview(LastName.Background);
            ControlStyling.StyleTextField(Email.Field, ProfileStrings.EmailPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(Email.Background);
            Email.Field.EditingDidBegin += (sender, e) => { Dirty = true; };

            CellPhone = new StyledTextField();
            ScrollView.AddSubview(CellPhone.Background);
            CellPhone.Field.AutocapitalizationType = UITextAutocapitalizationType.None;
            CellPhone.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(CellPhone.Field, ProfileStrings.CellPhonePlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(CellPhone.Background);
            CellPhone.Field.EditingDidBegin += (sender, e) => { Dirty = true; };


            Street = new StyledTextField();
            ScrollView.AddSubview(Street.Background);
            Street.Field.AutocapitalizationType = UITextAutocapitalizationType.Words;
            Street.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(Street.Field, ProfileStrings.StreetPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(Street.Background);
            Street.Field.EditingDidBegin += (sender, e) => { Dirty = true; };

            City = new StyledTextField();
            ScrollView.AddSubview(City.Background);
            City.Field.AutocapitalizationType = UITextAutocapitalizationType.Words;
            City.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(City.Field, ProfileStrings.CityPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(City.Background);
            City.Field.EditingDidBegin += (sender, e) => { Dirty = true; };

            State = new StyledTextField();
            ScrollView.AddSubview(State.Background);
            State.Field.AutocapitalizationType = UITextAutocapitalizationType.Words;
            State.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(State.Field, ProfileStrings.StatePlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(State.Background);
            State.Field.EditingDidBegin += (sender, e) => { Dirty = true; };

            Zip = new StyledTextField();
            ScrollView.AddSubview(Zip.Background);
            Zip.Field.AutocapitalizationType = UITextAutocapitalizationType.None;
            Zip.Field.AutocorrectionType     = UITextAutocorrectionType.No;
            ControlStyling.StyleTextField(Zip.Field, ProfileStrings.ZipPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(Zip.Background);
            Zip.Field.EditingDidBegin += (sender, e) => { Dirty = true; };


            // Gender
            Gender = new StyledTextField();
            ScrollView.AddSubview(Gender.Background);
            Gender.Field.UserInteractionEnabled = false;
            ControlStyling.StyleTextField(Gender.Field, ProfileStrings.GenderPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(Gender.Background);

            GenderButton = new UIButton( );
            ScrollView.AddSubview(GenderButton);
            GenderButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                // don't allow multiple pickers
                if (GenderPicker.Revealed == false && BirthdatePicker.Revealed == false)
                {
                    HideKeyboard( );

                    // if they have a gender selected, default to that.
                    if (string.IsNullOrWhiteSpace(Gender.Field.Text) == false)
                    {
                        ((UIPickerView)GenderPicker.Picker).Select(RockLaunchData.Instance.Data.Genders.IndexOf(Gender.Field.Text) - 1, 0, false);
                    }

                    GenderPicker.TogglePicker(true);
                }
            };
            //

            // Birthday
            Birthdate = new StyledTextField( );
            ScrollView.AddSubview(Birthdate.Background);
            Birthdate.Field.UserInteractionEnabled = false;
            ControlStyling.StyleTextField(Birthdate.Field, ProfileStrings.BirthdatePlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(Birthdate.Background);

            BirthdayButton = new UIButton( );
            ScrollView.AddSubview(BirthdayButton);
            BirthdayButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                // don't allow multiple pickers
                if (GenderPicker.Revealed == false && BirthdatePicker.Revealed == false)
                {
                    HideKeyboard( );

                    // setup the default date time to display
                    DateTime initialDate = DateTime.Now;
                    if (string.IsNullOrWhiteSpace(Birthdate.Field.Text) == false)
                    {
                        initialDate = DateTime.Parse(Birthdate.Field.Text);
                    }

                    ((UIDatePicker)BirthdatePicker.Picker).Date = initialDate.DateTimeToNSDate( );
                    BirthdatePicker.TogglePicker(true);
                }
            };
            //


            // setup the home campus chooser
            HomeCampus = new StyledTextField( );
            ScrollView.AddSubview(HomeCampus.Background);
            HomeCampus.Field.UserInteractionEnabled = false;
            ControlStyling.StyleTextField(HomeCampus.Field, ProfileStrings.CampusPlaceholder, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            ControlStyling.StyleBGLayer(HomeCampus.Background);

            HomeCampusButton = new UIButton( );
            ScrollView.AddSubview(HomeCampusButton);
            HomeCampusButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                UIAlertController actionSheet = UIAlertController.Create(ProfileStrings.SelectCampus_SourceTitle,
                                                                         ProfileStrings.SelectCampus_SourceDescription,
                                                                         UIAlertControllerStyle.ActionSheet);

                // if the device is a tablet, anchor the menu
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                {
                    actionSheet.PopoverPresentationController.SourceView = HomeCampusButton;
                    actionSheet.PopoverPresentationController.SourceRect = HomeCampusButton.Bounds;
                }

                // for each campus, create an entry in the action sheet, and its callback will assign
                // that campus index to the user's viewing preference
                for (int i = 0; i < RockLaunchData.Instance.Data.Campuses.Count; i++)
                {
                    UIAlertAction campusAction = UIAlertAction.Create(RockLaunchData.Instance.Data.Campuses[i].Name, UIAlertActionStyle.Default, delegate(UIAlertAction obj)
                    {
                        // update the home campus text and flag as dirty
                        HomeCampus.Field.Text = obj.Title;
                        Dirty = true;
                    });

                    actionSheet.AddAction(campusAction);
                }

                // let them cancel, too
                UIAlertAction cancelAction = UIAlertAction.Create(GeneralStrings.Cancel, UIAlertActionStyle.Cancel, delegate { });
                actionSheet.AddAction(cancelAction);

                PresentViewController(actionSheet, true, null);
            };

            DoneButton = new UIButton( );
            ScrollView.AddSubview(DoneButton);
            ControlStyling.StyleButton(DoneButton, ProfileStrings.DoneButtonTitle, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            DoneButton.SizeToFit( );

            LogoutButton = new UIButton( );
            ScrollView.AddSubview(LogoutButton);
            LogoutButton.SetTitleColor(Rock.Mobile.UI.Util.GetUIColor(ControlStylingConfig.TextField_PlaceholderTextColor), UIControlState.Normal);
            LogoutButton.SetTitle(ProfileStrings.LogoutButtonTitle, UIControlState.Normal);
            LogoutButton.SizeToFit( );


            // setup the pickers
            UILabel genderPickerLabel = new UILabel( );

            ControlStyling.StyleUILabel(genderPickerLabel, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            genderPickerLabel.Text = ProfileStrings.SelectGenderLabel;

            GenderPicker = new PickerAdjustManager(View, ScrollView, genderPickerLabel, Gender.Background);
            UIPickerView genderPicker = new UIPickerView();

            genderPicker.Model = new GenderPickerModel()
            {
                Parent = this
            };
            GenderPicker.SetPicker(genderPicker);


            UILabel birthdatePickerLabel = new UILabel( );

            ControlStyling.StyleUILabel(birthdatePickerLabel, ControlStylingConfig.Font_Regular, ControlStylingConfig.Medium_FontSize);
            birthdatePickerLabel.Text = ProfileStrings.SelectBirthdateLabel;
            BirthdatePicker           = new PickerAdjustManager(View, ScrollView, birthdatePickerLabel, Birthdate.Background);

            UIDatePicker datePicker = new UIDatePicker();

            datePicker.SetValueForKey(UIColor.White, new NSString("textColor"));
            datePicker.Mode          = UIDatePickerMode.Date;
            datePicker.MinimumDate   = new DateTime(1900, 1, 1).DateTimeToNSDate( );
            datePicker.MaximumDate   = DateTime.Now.DateTimeToNSDate( );
            datePicker.ValueChanged += (object sender, EventArgs e) =>
            {
                NSDate pickerDate = ((UIDatePicker)sender).Date;
                Birthdate.Field.Text = string.Format("{0:MMMMM dd yyyy}", pickerDate.NSDateToDateTime( ));
            };
            BirthdatePicker.SetPicker(datePicker);


            // Allow the return on username and password to start
            // the login process
            NickName.Field.ShouldReturn += TextFieldShouldReturn;
            LastName.Field.ShouldReturn += TextFieldShouldReturn;

            Email.Field.ShouldReturn += TextFieldShouldReturn;

            // If submit is pressed with dirty changes, prompt the user to save them.
            DoneButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                // dont' allow changes while the profile is refreshing.
                if (RefreshingProfile == false)
                {
                    if (GenderPicker.Revealed == false && BirthdatePicker.Revealed == false)
                    {
                        if (Dirty == true)
                        {
                            // make sure the input is valid before asking them what they want to do.
                            if (ValidateInput( ))
                            {
                                // if there were changes, create an action sheet for them to confirm.
                                UIAlertController actionSheet = UIAlertController.Create(ProfileStrings.SubmitChangesTitle,
                                                                                         null,
                                                                                         UIAlertControllerStyle.ActionSheet);

                                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                                {
                                    actionSheet.PopoverPresentationController.SourceView = DoneButton;
                                    actionSheet.PopoverPresentationController.SourceRect = DoneButton.Bounds;
                                }

                                UIAlertAction submitAction = UIAlertAction.Create(GeneralStrings.Yes, UIAlertActionStyle.Default, delegate
                                {
                                    Dirty = false; SubmitChanges( ); Springboard.ResignModelViewController(this, null);
                                });
                                actionSheet.AddAction(submitAction);

                                UIAlertAction noSubmitAction = UIAlertAction.Create(GeneralStrings.No, UIAlertActionStyle.Destructive, delegate
                                {
                                    Dirty = false; Springboard.ResignModelViewController(this, null);
                                });
                                actionSheet.AddAction(noSubmitAction);

                                // let them cancel, too
                                UIAlertAction cancelAction = UIAlertAction.Create(GeneralStrings.Cancel, UIAlertActionStyle.Cancel, delegate { });
                                actionSheet.AddAction(cancelAction);

                                PresentViewController(actionSheet, true, null);
                            }
                        }
                        else
                        {
                            Springboard.ResignModelViewController(this, null);
                        }
                    }
                    else
                    {
                        GenderPicker.TogglePicker(false);
                        BirthdatePicker.TogglePicker(false);
                        Dirty = true;
                    }
                }
            };

            // On logout, make sure the user really wants to log out.
            LogoutButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                // don't allow changes while the profile is refreshing
                if (RefreshingProfile == false)
                {
                    if (GenderPicker.Revealed == false && BirthdatePicker.Revealed == false)
                    {
                        // if they tap logout, and confirm it
                        UIAlertController actionSheet = UIAlertController.Create(ProfileStrings.LogoutTitle,
                                                                                 null,
                                                                                 UIAlertControllerStyle.ActionSheet);

                        if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
                        {
                            actionSheet.PopoverPresentationController.SourceView = LogoutButton;
                            actionSheet.PopoverPresentationController.SourceRect = LogoutButton.Bounds;
                        }

                        UIAlertAction logoutAction = UIAlertAction.Create(GeneralStrings.Yes, UIAlertActionStyle.Destructive, delegate
                        {
                            // then log them out.
                            RockMobileUser.Instance.LogoutAndUnbind( );

                            Springboard.ResignModelViewController(this, null);
                        });
                        actionSheet.AddAction(logoutAction);

                        // let them cancel, too
                        UIAlertAction cancelAction = UIAlertAction.Create(GeneralStrings.Cancel, UIAlertActionStyle.Cancel, delegate { });
                        actionSheet.AddAction(cancelAction);

                        PresentViewController(actionSheet, true, null);
                    }
                    else
                    {
                        GenderPicker.TogglePicker(false);
                        BirthdatePicker.TogglePicker(false);
                        Dirty = true;
                    }
                }
            };

            ResultView = new UIResultView(ScrollView, View.Bounds.ToRectF( ),
                                          delegate
            {
                Springboard.ResignModelViewController(this, null);
            });

            Dirty = false;

            // logged in sanity check.
            if (RockMobileUser.Instance.LoggedIn == false)
            {
                throw new Exception("A user must be logged in before viewing a profile. How did you do this?");
            }
        }
        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";

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

            PublicCloudDatabase.AddOperation(queryOp);
        }
예제 #19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (ViewModel == null)
            {
                return;
            }

            if (!DeviceHelper.IsPad)
            {
                AdjustFontSize(this.View);
            }

            //SetBackButtonTitle("Back");

            mToastToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <ToastMessage>((ToastMessage message) =>
            {
                if (message.Sender != ViewModel)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(message.Message))
                {
                    var progressHud = new ProgressHUD()
                    {
                        ForceiOS6LookAndFeel = true
                    };

                    progressHud.ShowToast(message.Message, ProgressHUD.MaskType.None, ProgressHUD.ToastPosition.Bottom, 1500);

                    progressHud.Dispose();
                    progressHud = null;
                }
            });

            mProgressToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <ProgressMessage>(message =>
            {
                if (message.Sender != ViewModel)
                {
                    return;
                }

                if (message.IsShow)
                {
                    if (mProgressHud == null)
                    {
                        mProgressHud = new ProgressHUD()
                        {
                            ForceiOS6LookAndFeel = true
                        }
                    }
                    ;

                    mProgressHud.Show(message.Message, -1, message.IsAllowInteraction ? ProgressHUD.MaskType.None : ProgressHUD.MaskType.Clear);
                }
                else
                {
                    if (mProgressHud != null)
                    {
                        mProgressHud.Dismiss();
                        mProgressHud.Dispose();
                        mProgressHud = null;
                    }
                }
            });

            mAlertToken = Mvx.Resolve <IMvxMessenger>().SubscribeOnMainThread <AlertMessage>(message =>
            {
                if (message.Sender != ViewModel)
                {
                    return;
                }

                if (mAlertView != null)
                {
                    mAlertView.DismissWithClickedButtonIndex(-1, false);
                    if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                    {
                        mAlertView.Dismissed -= AlertViewDismissed;
                        mAlertView.Dispose();
                        mAlertView = null;
                    }
                }

                //TODO : use UIAlertView in iOS 7.x
                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
                {
                    //  show alert view with more than 1 buttons (e.g OK and Cancel )
                    if (message.OtherTitles != null && message.OtherActions != null)
                    {
                        if (mAlertView == null)
                        {
                            mAlertView = new UIAlertView(message.Title, message.Message, null, message.CancelTitle);
                        }

                        if (message.OtherTitles.Length == message.OtherActions.Length)
                        {
                            foreach (var title in message.OtherTitles)
                            {
                                mAlertView.AddButton(title);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Please check your message constructor");
                            return;
                        }

                        mAlertView.Clicked += (object sender, UIButtonEventArgs e) =>
                        {
                            if (e.ButtonIndex != 0)
                            {
                                message.OtherActions[(int)e.ButtonIndex - 1]();
                            }
                            else
                            {
                                if (message.CancelAction != null)
                                {
                                    message.CancelAction();
                                }
                            }
                        };

                        mAlertView.Dismissed += AlertViewDismissed;

                        mAlertView.Show();
                    }
                    //this is just a normal alert view :)
                    else
                    {
                        if (mAlertView == null)
                        {
                            mAlertView = new UIAlertView(message.Title, message.Message, null, message.CancelTitle);
                        }

                        mAlertView.Clicked += (object sender, UIButtonEventArgs e) =>
                        {
                            if (message.CancelAction != null)
                            {
                                message.CancelAction();
                            }
                        };

                        mAlertView.Dismissed += (object sender, UIButtonEventArgs e) =>
                        {
                            if (mAlertView != null)
                            {
                                mAlertView.Dispose();
                                mAlertView = null;
                            }
                        };

                        mAlertView.Show();
                    }
                }
                else
                {
                    //show alert view with more than 1 buttons (e.g OK and Cancel )
                    if (message.OtherTitles != null && message.OtherActions != null)
                    {
                        UIAlertController alertController = UIAlertController.Create(message.Title, message.Message, UIAlertControllerStyle.Alert);
                        UIAlertAction cancelAction        = UIAlertAction.Create(message.CancelTitle, UIAlertActionStyle.Cancel,
                                                                                 action =>
                        {
                            if (message.CancelAction != null)
                            {
                                message.CancelAction();
                            }
                        });
                        alertController.AddAction(cancelAction);

                        if (message.OtherTitles.Length == message.OtherActions.Length)
                        {
                            for (int i = 0; i < message.OtherTitles.Length; i++)
                            {
                                UIAlertAction alertAction = UIAlertAction.Create(message.OtherTitles[i], UIAlertActionStyle.Default,
                                                                                 action =>
                                {
                                    if ((i - 1 >= 0) && (message.OtherActions[i - 1] != null))
                                    {
                                        message.OtherActions[i - 1]();
                                    }
                                });
                                alertController.AddAction(alertAction);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Please check your message constructor");
                            return;
                        }

                        PresentViewController(alertController, true, null);
                    }
                    //this is just a normal alert view :)
                    else
                    {
                        UIAlertController alertController = UIAlertController.Create(message.Title, message.Message, UIAlertControllerStyle.Alert);
                        UIAlertAction cancelAction        = UIAlertAction.Create(message.CancelTitle, UIAlertActionStyle.Cancel,
                                                                                 action =>
                        {
                            if (message.CancelAction != null)
                            {
                                message.CancelAction();
                            }
                        });

                        alertController.AddAction(cancelAction);

                        PresentViewController(alertController, true, null);
                    }
                }
            });
        }
            // 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();
                    }
                });
            }
        // Handle the OnMapInfoEntered event from the item input UI.
        // MapSavedEventArgs contains the title, description, and tags that were entered.
        private async void MapItemInfoEntered(object sender, MapSavedEventArgs e)
        {
            // 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   title       = e.Title;
                string   description = e.Description;
                string[] tags        = e.Tags;

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

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

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

                    // Report a successful save.
                    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 " + e.Title, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
            finally
            {
                // Get rid of the item input controls.
                _mapInfoUi.Hide();
                _mapInfoUi = null;

                // Hide the progress bar.
                _activityIndicator.StopAnimating();
            }
        }
예제 #22
0
        public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
        {
            switch (editingStyle)
            {
            case UITableViewCellEditingStyle.Delete:

                UIAlertController actionSheetAlert = UIAlertController.Create(
                    "Menu", "Select An Action", UIAlertControllerStyle.ActionSheet);
                actionSheetAlert.AddAction(UIAlertAction.Create("Email", UIAlertActionStyle.Default, (obj) =>
                {
                    if (MFMailComposeViewController.CanSendMail)
                    {
                        var passengers = cards[indexPath.Row].getPassengers();
                        List <String> actualPassengers = new List <string>();
                        foreach (var person in passengers)
                        {
                            if (person != "")
                            {
                                actualPassengers.Add(person);
                            }
                        }
                        String passString = "Passengers: \n";
                        foreach (var passenger in actualPassengers)
                        {
                            passString += passenger + "\n";
                        }
                        var dateOut     = cards[indexPath.Row].dateOut;
                        var dateIn      = cards[indexPath.Row].dateOut;
                        var destination = cards[indexPath.Row].destination;
                        var hobbsIn     = cards[indexPath.Row].hobbsIn;
                        var hobbsOut    = cards[indexPath.Row].hobbsOut;
                        var hobbsTotal  = cards[indexPath.Row].totalHobbs;
                        var cash        = cards[indexPath.Row].cashSpent;
                        var flighttype  = cards[indexPath.Row].flightType;
                        var pilot       = cards[indexPath.Row].pilot;
                        var plane       = cards[indexPath.Row].planeType;
                        var lease       = cards[indexPath.Row].leaseName;

                        String message = string.Format("Date Out =    {0} \n " +
                                                       "Date In =     {1} \n" +
                                                       "Destination = {2} \n" +
                                                       "Hobbs In =    {3} \n" +
                                                       "Hobbs Out =   {4} \n" +
                                                       "Total Hobbs = {5}\n " +
                                                       "Cash Spent =  {6} \n" +
                                                       "Flight Type = {7} \n" +
                                                       "Pilot =       {8}\n" +
                                                       "Plane =       {9}\n" +
                                                       "Lease =       {10} \n", dateOut, dateIn,
                                                       destination, hobbsIn, hobbsOut, hobbsTotal,
                                                       cash, flighttype, pilot, plane, lease);
                        String body    = message + passString;
                        mailController = new MFMailComposeViewController();
                        mailController.SetToRecipients(new string[] { "*****@*****.**" });
                        mailController.SetSubject("Flight Card");
                        mailController.SetMessageBody("Flight card information:  \n " + body, false);
                        mailController.Finished += (object s,
                                                    MFComposeResultEventArgs args) =>
                        {
                            Console.WriteLine(args.Result.ToString());
                            args.Controller.DismissViewController(true, null);
                        };
                        vc.PresentViewController(mailController, true, null);
                    }
                }));
                actionSheetAlert.AddAction(UIAlertAction.Create("Edit", UIAlertActionStyle.Default, (obj) =>
                {
                    DataManip.SetIsUpdate(true);
                    DataManip.SetEditCard(cards[indexPath.Row]);

                    UIStoryboard board        = UIStoryboard.FromName("Main", null);
                    UIViewController ctrl     = (UIViewController)board.InstantiateViewController("Add");
                    ctrl.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal;
                    vc.PresentViewController(ctrl, true, null);
                }));
                actionSheetAlert.AddAction(UIAlertAction.Create("Delete", UIAlertActionStyle.Default, (obj) =>
                {
                    DataManip.deleteRecordFromFlightCards(cards[indexPath.Row]);
                    cards.RemoveAt(indexPath.Row);
                    tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
                }));

                actionSheetAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (obj) => {}));
                vc.PresentViewController(actionSheetAlert, true, null);
                tableView.DeselectRow(indexPath, true);
                break;

            case UITableViewCellEditingStyle.None:
                Console.WriteLine("commit editing style none called");
                break;
            }
        }
        /// <inheritdoc />
        public override void Show(string caption, object content, ButtonConfig[] buttonConfigs, bool isFullScreen = false)
        {
            Guard.ArgumentNotNull(() => buttonConfigs);

            var stringContent = content as string;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                var alertController = UIAlertController.Create(caption, string.Empty, UIAlertControllerStyle.Alert);
                if (stringContent != null)
                {
                    alertController.Message = stringContent;
                }

                var view = content as UIView;
                if (view != null)
                {
                    UIViewController v = new UIViewController();
                    v.View = view;
                    alertController.SetValueForKey(v, new NSString("contentViewController"));

                    //alertController.View.AddSubview(view);
                }

                foreach (var buttonConfig in buttonConfigs)
                {
                    var alertAction = UIAlertAction.Create(buttonConfig.Text, UIAlertActionStyle.Default, x => buttonConfig.Action());

                    EventHandler <bool> buttonConfigOnEnabledChanged = null;
                    buttonConfigOnEnabledChanged = (sender, isEnabled) => { alertAction.Enabled = isEnabled; };
                    buttonConfig.EnabledChanged += buttonConfigOnEnabledChanged;
                    alertAction.Enabled          = buttonConfig.IsEnabled;
                    alertController.AddAction(alertAction);
                }

                this.dispatcherService.CheckBeginInvokeOnUI(() => { UIApplication.SharedApplication.PresentInternal(alertController); });
            }
            else
            {
                var alertView = new UIAlertView
                {
                    AlertViewStyle = UIAlertViewStyle.Default,
                    Title          = caption
                };

                if (stringContent != null)
                {
                    alertView.Message = stringContent;
                }

                var view = content as UIView;
                if (view != null)
                {
                    alertView.AddSubview(view);
                }

                foreach (var buttonConfig in buttonConfigs)
                {
                    alertView.AddButton(buttonConfig.Text);
                }

                alertView.Clicked += (s, e) => { buttonConfigs[e.ButtonIndex].Action(); };

                this.dispatcherService.CheckBeginInvokeOnUI(() => { alertView.Show(); });
            }
        }
예제 #24
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.


            btnalerta1.TouchUpInside += delegate {
                //crear la alerta
                var alerta = UIAlertController.Create("Titulo", "Este es un mensaje", UIAlertControllerStyle.Alert);
                //accion
                alerta.AddAction(UIAlertAction.Create("Aceptar", UIAlertActionStyle.Default, null));
                //mostrar alerta
                PresentViewController(alerta, true, null);
            };

            btnalerta2.TouchUpInside += (object sender, EventArgs e) => {
                //Crear alerta
                var alerta = UIAlertController.Create("Titulo", "Es es un mensaje", UIAlertControllerStyle.Alert);

                //acciones
                alerta.AddAction(UIAlertAction.Create("Aceptar", UIAlertActionStyle.Default, (actionOk) => {
                    lblInformacion.Text = "Aceptar";
                }));

                alerta.AddAction(UIAlertAction.Create("Cancelar", UIAlertActionStyle.Cancel, (actionCancel) => {
                    lblInformacion.Text = "Cancelar";
                }));

                //mostrar alerta
                PresentViewController(alerta, true, null);
            };


            btnalerta3.TouchUpInside += (sender, e) => {
                //Crear la alerta
                var alerta = UIAlertController.Create("Titulo", "Nombre", UIAlertControllerStyle.Alert);

                //agregar una caja de texto
                alerta.AddTextField(textField =>
                {
                    textField.Placeholder     = "Escribe";
                    textField.BackgroundColor = UIColor.Red;
                    textField.TextColor       = UIColor.White;
                });

                //agrega las acciones
                var AccionCancelar = UIAlertAction.Create("Cancelar", UIAlertActionStyle.Cancel, (actionCacel) => {
                    lblInformacion.Text = "Cancelar";
                });

                var AccionAceptar = UIAlertAction.Create("Aceptar", UIAlertActionStyle.Default, (actionOk) => {
                    lblInformacion.Text = string.Format("Aceptar {0}", alerta.TextFields[0].Text);
                });

                alerta.AddAction(AccionCancelar);
                alerta.AddAction(AccionAceptar);

                //Present Alert
                PresentViewController(alerta, true, null);
            };

            btnalerta4.TouchUpInside += (object sender, EventArgs e) => {
                // crear alerta
                UIAlertController actionSheetAlert = UIAlertController.Create("Action Sheet", "Selecciona un item", UIAlertControllerStyle.ActionSheet);

                // se agregan las acciones
                actionSheetAlert.AddAction(UIAlertAction.Create("Item One", UIAlertActionStyle.Default, (action) => Console.WriteLine("Item One pressed.")));

                actionSheetAlert.AddAction(UIAlertAction.Create("Item Two", UIAlertActionStyle.Default, (action) => Console.WriteLine("Item Two pressed.")));

                actionSheetAlert.AddAction(UIAlertAction.Create("Item Three", UIAlertActionStyle.Default, (action) => Console.WriteLine("Item Three pressed.")));

                actionSheetAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => Console.WriteLine("Cancel button pressed.")));

                // mostrar un popover
                UIPopoverPresentationController presentationPopover = actionSheetAlert.PopoverPresentationController;
                if (presentationPopover != null)
                {
                    presentationPopover.SourceView = this.View;
                    presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
                }

                // mostrar alerta
                this.PresentViewController(actionSheetAlert, true, null);
            };
        }
예제 #25
0
 public void ErrorAlert()
 {
     okAlertController = UIAlertController.Create(null, alertMessage, UIAlertControllerStyle.Alert);
     okAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
     PresentViewController(okAlertController, true, null);
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();


            birthlbl.TextColor = UIColor.FromRGB(112, 112, 112);


            NavigationController.NavigationBarHidden = true;


            backButton.TouchUpInside += (sender, e) => {
                ViewModel.BackSignup2();
            };

            var screenTap1 = new UITapGestureRecognizer(() =>
            {
                datePicker.ResignFirstResponder();
            });

            this.View.AddGestureRecognizer(screenTap1);

            nextButton.TouchUpInside += (sender, e) => {
                if (!string.IsNullOrEmpty(ViewModel.gender) && !string.IsNullOrEmpty(datePicker.Text))
                {
                    //ViewModel.date_of_birth = datePicker.Text;

                    ViewModel.ShowSignup4();
                }
                else if (string.IsNullOrEmpty(ViewModel.gender))

                {
                    var okAlertController = UIAlertController.Create("Error message", "Please select sexe", UIAlertControllerStyle.Alert);

                    //Add Action
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    // Present Alert
                    PresentViewController(okAlertController, true, null);
                }

                else if (string.IsNullOrEmpty(datePicker.Text))

                {
                    var okAlertController = UIAlertController.Create("Error message", "Please select date of birth", UIAlertControllerStyle.Alert);

                    //Add Action
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    // Present Alert
                    PresentViewController(okAlertController, true, null);
                }
            };

            malebutton.TouchUpInside += (sender, e) => {
                malebutton.SetBackgroundImage(UIImage.FromBundle("male_selected"), UIControlState.Normal);
                femaleButton.SetBackgroundImage(UIImage.FromBundle("Female"), UIControlState.Normal);
                otherButton.SetBackgroundImage(UIImage.FromBundle("Other"), UIControlState.Normal);
                ViewModel.gender = "MALE";
            };

            femaleButton.TouchUpInside += (sender, e) => {
                femaleButton.SetBackgroundImage(UIImage.FromBundle("female_selected"), UIControlState.Normal);
                otherButton.SetBackgroundImage(UIImage.FromBundle("Other"), UIControlState.Normal);
                malebutton.SetBackgroundImage(UIImage.FromBundle("Male"), UIControlState.Normal);
                ViewModel.gender = "FEMALE";
            };

            otherButton.TouchUpInside += (sender, e) => {
                otherButton.SetBackgroundImage(UIImage.FromBundle("other_selected"), UIControlState.Normal);
                femaleButton.SetBackgroundImage(UIImage.FromBundle("Female"), UIControlState.Normal);
                malebutton.SetBackgroundImage(UIImage.FromBundle("Male"), UIControlState.Normal);
                ViewModel.gender = "OTHER";
            };



            UIDatePicker dpPurchaseDate;

            dpPurchaseDate                        = new UIDatePicker(new CGRect(0, 44.0f, this.View.Bounds.Width, 260));
            dpPurchaseDate.Mode                   = UIDatePickerMode.Date;
            dpPurchaseDate.MaximumDate            = NSDate.Now;
            dpPurchaseDate.TimeZone               = NSTimeZone.LocalTimeZone;
            dpPurchaseDate.UserInteractionEnabled = true;
            dpPurchaseDate.BackgroundColor        = UIColor.White;
            DateTime Date = new DateTime(1999, 01, 30);

            dpPurchaseDate.Date = DateTimeToNSDate(Date);



            var toolbar = new UIToolbar(new CGRect(0.0f, 0.0f, dpPurchaseDate.Frame.Size.Width, 44.0f));

            toolbar.BackgroundColor = UIColor.White;

            UIView pDateView;

            pDateView = new UIView(new CGRect(0, 0, this.View.Bounds.Width, 260 + 44.0f));

            toolbar.Items = new[]
            {
                new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                new UIBarButtonItem("Done",
                                    UIBarButtonItemStyle.Done,
                                    delegate {
                    Console.WriteLine("presing here");

                    datePicker.ResignFirstResponder();
                    dpPurchaseDate.ResignFirstResponder();
                    dpPurchaseDate.Hidden = true;
                    pDateView.Hidden      = true;
                    Console.WriteLine(dpPurchaseDate.Date.ToString());

                    var dateString = dpPurchaseDate.Date.ToString();
                    var formatted  = DateTime.Parse(dateString);
                    Console.WriteLine(formatted.ToString("dd,MM,yyyy"));
                    datePicker.Text = formatted.ToString("dd-MMMM-yyyy");

                    ViewModel.date_of_birth = formatted.ToString("yyyy-MM-dd");
                    //ResignFirstResponder();
                })
            };

            pDateView.AddSubview(dpPurchaseDate);
            pDateView.AddSubview(toolbar);


            datePicker.EditingDidBegin += delegate {
                pDateView.Hidden      = false;
                dpPurchaseDate.Hidden = false;
                datePicker.InputView  = pDateView;
            };
            var screenTap = new UITapGestureRecognizer(() =>
            {
                datePicker.ResignFirstResponder();
                dpPurchaseDate.ResignFirstResponder();
                dpPurchaseDate.Hidden = true;
                pDateView.Hidden      = true;
                Console.WriteLine(dpPurchaseDate.Date.ToString());

                var dateString = dpPurchaseDate.Date.ToString();
                var formatted  = DateTime.Parse(dateString);
                Console.WriteLine(formatted.ToString("dd,MM,yyyy"));
                datePicker.Text = formatted.ToString("dd-MMMM-yyyy");

                ViewModel.date_of_birth = formatted.ToString("yyyy-MM-dd");
            });


            View.AddGestureRecognizer(screenTap);
        }
예제 #27
0
        /// <summary>
        /// Starts the download.
        /// </summary>
        /// <param name="publication">Publication.</param>
        /// <param name="publicationView">Publication view.</param>
        /// <param name="checkNetLimitation">If set to <c>true</c> check net limitation.</param>
        private async void StartDownload(Publication publication, PublicationView publicationView, bool checkNetLimitation = true)
        {
            string prevInfoStr       = publicationView.StatusLabel.Text;
            string downloadFailedMsg = "";

            if (publication.PublicationStatus == PublicationStatusEnum.NotDownloaded)
            {
                downloadFailedMsg = "Download Failed";
            }
            if (publication.PublicationStatus == PublicationStatusEnum.RequireUpdate)
            {
                downloadFailedMsg = "Update Failed";
            }

            publicationView.StatusLabel.Text = "Downloading";



            var pView = AppDisplayUtil.Instance.AppDelegateInstance.PublicationViewList.Find(pv => pv.P.BookId == publication.BookId);

            if (pView != null && pView != publicationView)
            {
                pView.RightTopView.ShowDownloadProgressView();
            }

            DownloadResult downloadResult = await PublicationUtil.Instance.DownloadPublicationByBookId(publication.BookId, publicationView.DownloadCancelTokenSource.Token, delegate(int downloadedProgress, long downloadSize) {
                //更新publication对应的所有view的下载进度及状态
                publicationView.UpdateDownloadProgress(downloadedProgress, downloadSize);
                if (pView != null && pView != publicationView)
                {
                    pView.UpdateDownloadProgress(downloadedProgress, downloadSize);
                }
            }, checkNetLimitation);

            switch (downloadResult.DownloadStatus)
            {
            case DownLoadEnum.OverLimitation:
                var overLimitationAlert = UIAlertController.Create("Download Over 20MB", "This Digital Looseleaf title is over 20MB. We recommend you connect to a Wi-Fi network to download it.", UIAlertControllerStyle.Alert);
                overLimitationAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
                overLimitationAlert.AddAction(UIAlertAction.Create("Download", UIAlertActionStyle.Default, alert => StartDownload(publication, publicationView, false)));
                PresentViewController(overLimitationAlert, true, null);
                break;

            case DownLoadEnum.Canceled:
                publicationView.StatusLabel.Text = downloadFailedMsg;
                if (pView != null && pView != publicationView)
                {
                    pView.P = publication;
                    pView.StatusLabel.Text = downloadFailedMsg;
                }
                break;

            case DownLoadEnum.Failure:
                publicationView.StatusLabel.Text = downloadFailedMsg;
                publicationView.RightTopView.RemoveActionSubview();
                publicationView.RightTopView.ShowDownloadActionView(publication, StartDownload, ShowConfirmCancelDownload, true);
                ShowAlert(downloadFailedMsg);
                break;

            case DownLoadEnum.NetDisconnected:
                publicationView.StatusLabel.Text = downloadFailedMsg;
                publicationView.RightTopView.RemoveActionSubview();
                publicationView.RightTopView.ShowDownloadActionView(publication, StartDownload, ShowConfirmCancelDownload, true);
                ShowAlert("Missing connection", "Sorry, there appears to be no Internet connection. A connection is required to complete this task.");
                break;

            case DownLoadEnum.Success:
                //update publication view after publication has been download(download date, practice area, subcategory etc)
                //UpdatePublicationViewInScrollView (publication, publicationView);
                publicationList = PublicationUtil.Instance.GetPublicationOffline();
                publication     = publicationList.Find(p => p.BookId == publication.BookId);             //Get latest publication meta data after it has been downloaded
                publication.PublicationStatus = PublicationStatusEnum.Downloaded;
                publicationView.P             = publication;
                if (pView != null && pView != publicationView)
                {
                    pView.P = publication;
                }
                break;
            }
        }
예제 #28
0
        // Fortryd kald
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);

            var regretAlertController = UIAlertController.Create(Strings.CallRegretTitle, Strings.CallRegretMessage, UIAlertControllerStyle.Alert);

            var regretAction = UIAlertAction.Create(Strings.OK, UIAlertActionStyle.Destructive, action =>
            {
                new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    // Get the selected call
                    var callEntity = CallEntities[indexPath.Row];

                    // Update status
                    callEntity.Status = (int)CallUtil.StatusCode.Canceled;

                    // Try update the call
                    try
                    {
                        // Put the async patient call here
                        ICall patientCall = new PatientCall();
                        patientCall.UpdateCall(callEntity);

                        vc.InvokeOnMainThread(() =>
                        {
                            // (Get a confirm message that the patient call was successfull)
                            new UIAlertView(Strings.CallRegretted, null, null, "OK", null).Show();

                            DataHandler.UpdateMyCallToLocalDatabase(new LocalDB(), callEntity);

                            // Reload data
                            SetCallEntities(callEntity);
                            tableView.ReloadData();
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("ERROR updaing call: " + ex.Message);

                        vc.InvokeOnMainThread(() =>
                        {
                            new UIAlertView(Strings.Error, Strings.ErrorSendingCall, null, "OK", null).Show();

                            return;
                        });
                    }
                })).Start();
            });

            // When user cancels the service
            var cancelAction = UIAlertAction.Create("Annullér", UIAlertActionStyle.Cancel, action =>
            {
                // Do nothing.
            });

            regretAlertController.AddAction(regretAction);
            regretAlertController.AddAction(cancelAction);

            // Display the alert
            vc.PresentViewController(regretAlertController, true, null);
        }
예제 #29
0
        /// <summary>
        /// Shows an alert with Textfields.
        /// For iOS 7 or before, an alert with a Textfield will be shown.
        /// </summary>
        /// <param name="title">The title of the alert.</param>
        /// <param name="message">Message to show to user.</param>
        /// <param name="fromViewController">From which view the alert will be presented.</param>
        /// <param name="okTitle">Title for Ok button.</param>
        /// <param name="placeholders">
        /// Placeholders to be shown in textfields. A Textfield will be added for each placeholder
        /// If null or an empty array is passed, a simple alert will be shown.
        /// </param>
        /// <param name="result">
        /// Action to be done when user press one button of alert.
        /// Will return all inputs from Textfields in order that were shown or null if Cancel button was tapped.
        /// </param>
        public static void ShowMessage(string title, string message, UIViewController fromViewController,
                                       string okTitle, string [] placeholders, UIAlertControllerTextFieldResultHandler result)
        {
            if (string.IsNullOrWhiteSpace(okTitle))
            {
                okTitle = "Ok";
            }

            if (placeholders == null || placeholders.Length == 0)
            {
                ShowMessage(title, message, fromViewController, okTitle);
                return;
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);

                foreach (var placeholder in placeholders)
                {
                    alert.AddTextField((textField) => {
                        textField.Placeholder   = placeholder;
                        textField.TextAlignment = UITextAlignment.Center;
                    });
                }

                alert.AddAction(UIAlertAction.Create(okTitle, UIAlertActionStyle.Default, (obj) => {
                    var textfields = alert.TextFields;
                    var inputs     = new string [textfields.Length];

                    for (int i = 0; i < textfields.Length; i++)
                    {
                        inputs [i] = textfields [i].Text;
                    }

                    result?.Invoke(false, inputs);
                }));

                alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (obj) => {
                    result?.Invoke(true, null);
                }));

                fromViewController.PresentViewController(alert, true, null);
            }
            else
            {
                var alert = new UIAlertView(title, message, null, "Cancel", okTitle)
                {
                    AlertViewStyle = UIAlertViewStyle.PlainTextInput
                };
                alert.Dismissed += (sender, e) => {
                    if (e.ButtonIndex == 0)
                    {
                        result?.Invoke(true, null);
                    }
                    else
                    {
                        var value = (sender as UIAlertView).GetTextField(0).Text;
                        result?.Invoke(false, new [] { value });
                    }
                };

                alert.Show();
            }
        }
예제 #30
0
        private async Task CalculateViewshed(MapPoint location)
        {
            // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a
            // user click on the map and then display the results back as a polygon fill graphics overlay. If there
            // is a problem with the execution of the geoprocessing task an error message will be displayed

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

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

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

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

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

            // Create the parameters that are passed to the used geoprocessing task
            GeoprocessingParameters myViewshedParameters =
                new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute);

            // Request the output features to use the same SpatialReference as the map view
            myViewshedParameters.OutputSpatialReference = _myMapView.SpatialReference;

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

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

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

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

                // Add all the results as a graphics to the map
                IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features;
                foreach (var myFeature in myViewshedAreas)
                {
                    _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry));
                }
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem
                if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null)
                {
                    // Report error
                    UIAlertController alert = UIAlertController.Create("Geoprocessing Error", myViewshedJob.Error.Message, UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                else
                {
                    // Report error
                    UIAlertController alert = UIAlertController.Create("Sample Error", ex.ToString(), UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            }
        }