public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            buttonLocation.TouchUpInside += (sender, e) => {
                var locator = new Geolocator { DesiredAccuracy = 50 };
                locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
                    var text = String.Format("Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude);
                    InvokeOnMainThread(() => LabelLocation.Text = text);
                });
            };

            buttonPicture.TouchUpInside += (sender, e) => {
                var camera = new MediaPicker ();

                if (!camera.IsCameraAvailable) {
                    Console.WriteLine("Camera unavailable!");
                    return;
                }

                var opts = new StoreCameraMediaOptions {
                    Name = "test.jpg",
                    Directory = "MiniHackDemo"
                };

                camera.TakePhotoAsync (opts).ContinueWith (t => {
                    if (t.IsCanceled)
                        return;

                    InvokeOnMainThread(() => imagePhoto.Image = UIImage.FromFile(t.Result.Path));
                });
            };
        }
Exemplo n.º 2
0
		public Intent GetTakePhotoUI (StoreCameraMediaOptions options)
		{
			if (!IsCameraAvailable)
				throw new NotSupportedException();

			VerifyOptions (options);

			int id = GetRequestId();
			return CreateMediaIntent (id, "image/*", MediaStore.ActionImageCapture, options, tasked: false);
		}
		internal MediaPickerDelegate (UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options)
		{
			this.viewController = viewController;
			this.source = sourceType;
			this.options = options ?? new StoreCameraMediaOptions();

			if (viewController != null) {
				UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
				this.observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidRotate);
			}
		}
Exemplo n.º 4
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

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

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.buttonLocation);
            LabelLocation = FindViewById<TextView>(Resource.Id.locationLabel);
            image = FindViewById<ImageView>(Resource.Id.imagePhoto);

            button.Click += delegate {

                var locator = new Geolocator(this) { DesiredAccuracy = 50 };
                locator.GetPositionAsync(timeout: 10000).ContinueWith(t =>
                {
                    var text = String.Format("Location : Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude);
                    this.RunOnUiThread(() => LabelLocation.Text = text);
                });
            };

            Button getimge = FindViewById<Button>(Resource.Id.buttonCamera);
            getimge.Click += delegate
            {
                var camera = new MediaPicker(this);

                if (!camera.IsCameraAvailable)
                {
                    Console.WriteLine("Camera unavailable!");
                    return;
                }

                var opts = new StoreCameraMediaOptions
                {
                    Name = "test.jpg",
                    Directory = "MiniHackDemo"
                };

                camera.TakePhotoAsync(opts).ContinueWith(t =>
                {
                    if (t.IsCanceled)
                        return;

                    using (var bmp = Android.Graphics.BitmapFactory.DecodeFile(t.Result.Path))
                    {
                        this.RunOnUiThread(() => image.SetImageBitmap(bmp));
                    }
                });
                
            };
        }
Exemplo n.º 5
0
		public Task<MediaFile> TakePhotoAsync (StoreCameraMediaOptions options)
		{
			options.VerifyOptions();

			var ntcs = new TaskCompletionSource<MediaFile> (options);
			if (Interlocked.CompareExchange (ref this.completionSource, ntcs, null) != null)
				throw new InvalidOperationException ("Only one operation can be active at a time");

			this.cameraCapture.Show();

			return ntcs.Task;
		}
Exemplo n.º 6
0
		public MediaPickerController GetTakePhotoUI (StoreCameraMediaOptions options)
		{
			if (!PhotosSupported)
				throw new NotSupportedException();
			if (!IsCameraAvailable)
				throw new NotSupportedException();
			
			VerifyCameraOptions (options);

			var d = new MediaPickerDelegate (null, UIImagePickerControllerSourceType.PhotoLibrary, options);
			return SetupController (d, UIImagePickerControllerSourceType.Camera, TypeImage, options);
		}
Exemplo n.º 7
0
		public async Task<MediaFile> TakePhotoAsync (StoreCameraMediaOptions options)
		{
			options.VerifyOptions();

			var capture = new CameraCaptureUI();
			var result = await capture.CaptureFileAsync (CameraCaptureUIMode.Photo).AsTask (false);
			if (result == null)
				throw new TaskCanceledException();

			StorageFolder folder = ApplicationData.Current.LocalFolder;

			string path = options.GetFilePath (folder.Path);
			folder = await StorageFolder.GetFolderFromPathAsync (Path.GetDirectoryName (path));
			string filename = Path.GetFileName (path);

			IStorageFile file = await result.CopyAsync (folder, filename, NameCollisionOption.GenerateUniqueName).AsTask (false);
			return new MediaFile (file.Path, () => file.OpenStreamForReadAsync().Result);
		}
    private void TakePhoto()
    {
      var picker = new MediaPicker(this);
      if (!picker.IsCameraAvailable)
      {
        Console.WriteLine("No Camera :(");
        return;
      }

      var options = new StoreCameraMediaOptions
      {
        Name = "temp.jpg",
        Directory = "flashcast"
      };

      var intent = picker.GetTakePhotoUI(options);

      StartActivityForResult(intent, 1);
    }
Exemplo n.º 9
0
        private async void addPhoto(bool takeNew)
        {
            //Capture photo file from view
            var picker  = new Xamarin.Media.MediaPicker();
            var options = new Xamarin.Media.StoreCameraMediaOptions();

            var       mediaFileSource = this.GetService <Core.Interfaces.IMediaFileSource>();
            MediaFile mediaFile       = null;

            try { mediaFile = await mediaFileSource.GetPhoto(takeNew); }
            catch { }

            if (mediaFile != null && !string.IsNullOrEmpty(mediaFile.Path))
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.Photo = new System.Windows.Media.Imaging.BitmapImage();
                    this.Photo.SetSource(mediaFile.GetStream());


                    var photoBase64 = string.Empty;
                    var wbmp        = new System.Windows.Media.Imaging.WriteableBitmap(this.Photo);

                    using (var ms = new System.IO.MemoryStream())
                    {
                        wbmp.SaveJpeg(ms, 640, 480, 0, 60);
                        photoBase64 = Convert.ToBase64String(ms.ToArray());
                    }

                    this.ViewModel.AddPhoto(photoBase64);

                    //Clean up!
                    mediaFile.Dispose();
                });
            }
        }
Exemplo n.º 10
0
		private static MediaPickerController SetupController (MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
		{
			var picker = new MediaPickerController (mpDelegate);
			picker.MediaTypes = new[] { mediaType };
			picker.SourceType = sourceType;

			if (sourceType == UIImagePickerControllerSourceType.Camera) {
				picker.CameraDevice = GetUICameraDevice (options.DefaultCamera);
				
				if (mediaType == TypeImage)
					picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
				else if (mediaType == TypeMovie) {
					StoreVideoOptions voptions = (StoreVideoOptions)options;
					
					picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
					picker.VideoQuality = GetQuailty (voptions.Quality);
					picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
				}
			}

			return picker;
		}
Exemplo n.º 11
0
		private void VerifyCameraOptions (StoreCameraMediaOptions options)
		{
			VerifyOptions (options);
			if (!Enum.IsDefined (typeof(CameraDevice), options.DefaultCamera))
				throw new ArgumentException ("options.Camera is not a member of CameraDevice");
		}
Exemplo n.º 12
0
		public override async void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			if (fileName == "") {
				fileName = "in-progress";
				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android
				if (!picker.IsCameraAvailable || !picker.PhotosSupported)
					Console.WriteLine ("No camera!");
				else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};
#if !VISUALSTUDIO
					#region new style
					pickerController = picker.GetTakePhotoUI (options);
					PresentViewController (pickerController, true, null);

					var pickerTask = pickerController.GetResultAsync ();
					await pickerTask;

					// We need to dismiss the controller ourselves
					await DismissViewControllerAsync (true); // woot! async-ified iOS method

					// User canceled or something went wrong
					if (pickerTask.IsCanceled || pickerTask.IsFaulted)
						return;

					// We get back a MediaFile
					MediaFile media = pickerTask.Result;
					fileName = media.Path;
					PhotoImageView.Image = new UIImage (fileName);
					SavePicture(fileName);

					#endregion
#else
					#region old style (deprecated)
					var t = picker.TakePhotoAsync (options); //.ContinueWith (t => {
					await t;
					if (t.IsCanceled) {
						Console.WriteLine ("User canceled");
						fileName = "cancelled";
						//InvokeOnMainThread(() =>{
						NavigationController.PopToRootViewController(false);
						//});
						return;
					}
					Console.WriteLine (t.Result.Path);
					fileName = t.Result.Path;
					//InvokeOnMainThread(() =>{
					PhotoImageView.Image = new UIImage (fileName);
					//});
					SavePicture(fileName);
					//});
					#endregion
#endif
				}
			} else if (fileName == "cancelled") {
				NavigationController.PopToRootViewController (true);
			} else {
				// populate screen with existing item
				PhotoImageView.Image = new UIImage (fileName);
				LocationText.Text = location;
			}

			var locator = new Geolocator { DesiredAccuracy = 50 };
			//            new Geolocator (this) { ... }; on Android
			var position = await locator.GetPositionAsync (timeout: 10000); //.ContinueWith (p => {
			Console.WriteLine ("Position Latitude: {0}", position.Latitude);
			Console.WriteLine ("Position Longitude: {0}", position.Longitude);

			location = string.Format("{0},{1}", position.Latitude, position.Longitude);

			LocationText.Text = location;
		}
Exemplo n.º 13
0
		public override async void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			if (fileName == "") {
				fileName = "in-progress";
				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android
				if (!picker.IsCameraAvailable || !picker.PhotosSupported)
					Console.WriteLine ("No camera!");
				else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};

					pickerController = picker.GetTakePhotoUI (options);
					PresentViewController (pickerController, true, null);

					MediaFile media;

					try 
					{
						var pickerTask = pickerController.GetResultAsync ();
						await pickerTask;

						// User canceled or something went wrong
						if (pickerTask.IsCanceled || pickerTask.IsFaulted) {
							fileName = "";
							return;
						}

						media = pickerTask.Result;
						fileName = media.Path;

						// We need to dismiss the controller ourselves
						await DismissViewControllerAsync (true); // woot! async-ified iOS method
					}
					catch(AggregateException ae) {
						fileName = "";
						Console.WriteLine("Error while huh", ae.Message);
					} catch(Exception e) {
						fileName = "";
						Console.WriteLine("Error while cancelling", e.Message);
					}

					if (String.IsNullOrEmpty (fileName)) {
						await DismissViewControllerAsync (true); 
					} else {
						PhotoImageView.Image = new UIImage (fileName);
						SavePicture(fileName);
					}
            	}
			}  
			else if (fileName == "cancelled") {
				NavigationController.PopToRootViewController (true);
			} else {
				// populate screen with existing item
				PhotoImageView.Image = FileExists(fileName) ? new UIImage (fileName) : null;
				LocationText.Text = location;
			}

			var locator = new Geolocator { DesiredAccuracy = 50 };
			var position = await locator.GetPositionAsync ( new CancellationToken(), false);
			Console.WriteLine ("Position Latitude: {0}", position.Latitude);
			Console.WriteLine ("Position Longitude: {0}", position.Longitude);

			location = string.Format("{0},{1}", position.Latitude, position.Longitude);

			LocationText.Text = location;
		}
Exemplo n.º 14
0
        private void MakePhoto_Click(object sender, EventArgs e)
        {
            try
            {
                var picker = new MediaPicker(this);
                if (!picker.IsCameraAvailable || !picker.PhotosSupported)
                {
                    ShowUnsupported();
                    return;
                }
                var store = new StoreCameraMediaOptions
                {
                    Directory = "Ersh",
                    Name = string.Format("ersh_{0}.jpg", DateTime.Now.Ticks + new Random().Next())
                };

                var intent = picker.GetTakePhotoUI(store);
                this.StartActivityForResult(intent, 2);
            }

            catch (Exception exception)
            {
                GaService.TrackAppException(this.Class, "MakePhoto_Click", exception, false);
            }

        }
Exemplo n.º 15
0
 public Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions param_options)
 {
     return(null);
 }
Exemplo n.º 16
0
        internal MediaPickerDelegate(UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options)
        {
            this.viewController = viewController;
            this.source         = sourceType;
            this.options        = options ?? new StoreCameraMediaOptions();

            if (viewController != null)
            {
                UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
                this.observer = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, DidRotate);
            }
        }
Exemplo n.º 17
0
		protected override async void OnResume ()
		{
			base.OnResume ();

			int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0);
			if(itemId > 0) {
				shareItem = App.Database.GetItem(itemId);

				fileName = shareItem.ImagePath;
				System.Console.WriteLine("Image path: " + fileName);
				Bitmap b = BitmapFactory.DecodeFile (fileName);
				// Display the bitmap
				photoImageView.SetImageBitmap (b);
				locationText.Text = shareItem.Location;
				return;
			}

			if (fileName == "") {
				fileName = "in-progress";
				var picker = new MediaPicker (this);
				//           new MediaPicker (); on iOS
				if (!picker.IsCameraAvailable)
					System.Console.WriteLine ("No camera!");
				else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};
#if !VISUALSTUDIO
					#region new style
					if (!picker.IsCameraAvailable || !picker.PhotosSupported) {
						ShowUnsupported();
						return;
					}

					Intent intent = picker.GetTakePhotoUI (options);

					StartActivityForResult (intent, 1);
					#endregion
#else 
					#region old style (deprecated)
					var t = picker.TakePhotoAsync (options); 
					await t;
					if (t.IsCanceled) {
						System.Console.WriteLine ("User canceled");
						fileName = "cancelled";
						// TODO: return to main screen
						StartActivity(typeof(MainScreen));
						return;
					}
					System.Console.WriteLine (t.Result.Path);
					fileName = t.Result.Path;
					fileNameThumb = fileName.Replace(".jpg", "_thumb.jpg"); 

					Bitmap b = BitmapFactory.DecodeFile (fileName);
					RunOnUiThread (() =>
					               {
						// Display the bitmap
						photoImageView.SetImageBitmap (b);

						// Cleanup any resources held by the MediaFile instance
						t.Result.Dispose();
					});
					var boptions = new BitmapFactory.Options {OutHeight = 128, OutWidth = 128};
					var newBitmap = await BitmapFactory.DecodeFileAsync (fileName, boptions);
					var @out = new System.IO.FileStream(fileNameThumb, System.IO.FileMode.Create);
					newBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, @out);
					//});
					#endregion
#endif
				}
			} 

			try {
				var locator = new Geolocator (this) { DesiredAccuracy = 50 };
				//            new Geolocator () { ... }; on iOS
				var position = await locator.GetPositionAsync (timeout: 10000);
				System.Console.WriteLine ("Position Latitude: {0}", position.Latitude);
				System.Console.WriteLine ("Position Longitude: {0}", position.Longitude);

				location = string.Format("{0},{1}", position.Latitude, position.Longitude);
				locationText.Text = location;
			} catch (Exception e) {
				System.Console.WriteLine ("Position Exception: " + e.Message);
			}
		}
Exemplo n.º 18
0
        private static MediaPickerController SetupController(MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
        {
            var picker = new MediaPickerController(mpDelegate);

            picker.MediaTypes = new[] { mediaType };
            picker.SourceType = sourceType;

            if (sourceType == UIImagePickerControllerSourceType.Camera)
            {
                picker.CameraDevice = GetUICameraDevice(options.DefaultCamera);

                if (mediaType == TypeImage)
                {
                    picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
                }
                else if (mediaType == TypeMovie)
                {
                    StoreVideoOptions voptions = (StoreVideoOptions)options;

                    picker.CameraCaptureMode    = UIImagePickerControllerCameraCaptureMode.Video;
                    picker.VideoQuality         = GetQuailty(voptions.Quality);
                    picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
                }
            }

            return(picker);
        }
Exemplo n.º 19
0
        private Task <MediaFile> TakeMedia(UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
        {
            UIWindow window = UIApplication.SharedApplication.KeyWindow;

            if (window == null)
            {
                throw new InvalidOperationException("There's no current active window");
            }

            UIViewController viewController = window.RootViewController;

            if (viewController == null)
            {
                window = UIApplication.SharedApplication.Windows.OrderByDescending(w => w.WindowLevel).FirstOrDefault(w => w.RootViewController != null);
                if (window == null)
                {
                    throw new InvalidOperationException("Could not find current view controller");
                }
                else
                {
                    viewController = window.RootViewController;
                }
            }

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }

            MediaPickerDelegate ndelegate = new MediaPickerDelegate(viewController, sourceType, options);
            var od = Interlocked.CompareExchange(ref this.pickerDelegate, ndelegate, null);

            if (od != null)
            {
                throw new InvalidOperationException("Only one operation can be active at at time");
            }

            var picker = SetupController(ndelegate, sourceType, mediaType);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                ndelegate.Popover          = new UIPopoverController(picker);
                ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate(ndelegate, picker);
                ndelegate.DisplayPopover();
            }
            else
            {
                viewController.PresentModalViewController(picker, true);
            }

            return(ndelegate.Task.ContinueWith(t => {
                if (this.popover != null)
                {
                    this.popover.Dispose();
                    this.popover = null;
                }

                Interlocked.Exchange(ref this.pickerDelegate, null);
                return t;
            }).Unwrap());
        }
Exemplo n.º 20
0
		private Task<MediaFile> GetMediaAsync (UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
		{
			UIWindow window = UIApplication.SharedApplication.KeyWindow;
			if (window == null)
				throw new InvalidOperationException ("There's no current active window");

			UIViewController viewController = window.RootViewController;

			if (viewController == null) {
				window = UIApplication.SharedApplication.Windows.OrderByDescending (w => w.WindowLevel).FirstOrDefault (w => w.RootViewController != null);
				if (window == null)
					throw new InvalidOperationException ("Could not find current view controller");
				else
					viewController = window.RootViewController;	
			}

			while (viewController.PresentedViewController != null)
				viewController = viewController.PresentedViewController;

			MediaPickerDelegate ndelegate = new MediaPickerDelegate (viewController, sourceType, options);
			var od = Interlocked.CompareExchange (ref this.pickerDelegate, ndelegate, null);
			if (od != null)
				throw new InvalidOperationException ("Only one operation can be active at at time");

			var picker = SetupController (ndelegate, sourceType, mediaType, options);

			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary) {	
				ndelegate.Popover = new UIPopoverController (picker);
				ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate (ndelegate, picker);
				ndelegate.DisplayPopover();
			} else
				viewController.PresentViewController (picker, true, null);

			return ndelegate.Task.ContinueWith (t => {
				if (this.popover != null) {
					this.popover.Dispose();
					this.popover = null;
				}
					
				Interlocked.Exchange (ref this.pickerDelegate, null);
				return t;
			}).Unwrap();
		}
        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView (inflater, container, savedInstanceState);
            var view = inflater.Inflate (Resource.Layout.ConfirmationsLayout, null, true);
            signatureImage = view.FindViewById<ImageView> (Resource.Id.confirmationsSignature);

            photoListView = view.FindViewById<ListView> (Resource.Id.confirmationPhotoList);
            photoListView.ItemClick += (sender, e) => {
                var image = view.FindViewById<ImageView> (Resource.Id.photoListViewImage);
                if (image != null) {
                    int index = (int)image.Tag;
                    var photo = Photos.ElementAtOrDefault (index);
                    photoDialog = new PhotoDialog (Activity);
                    photoDialog.Activity = Activity;
                    photoDialog.Assignment = Assignment;
                    photoDialog.Photo = photo;
                    photoDialog.Show ();
                }
            };

            var addPhoto = view.FindViewById<Button> (Resource.Id.confirmationsAddPhoto);
            if (Assignment != null) {
                addPhoto.Enabled = !Assignment.IsHistory;
            }
            addPhoto.Click += (sender, e) => {
                var choices = new List<string> ();
                choices.Add (Resources.GetString (Resource.String.Gallery));
                if (mediaPicker.IsCameraAvailable) {
                    choices.Add (Resources.GetString (Resource.String.Camera));
                }
                AlertDialog.Builder takePictureDialog = new AlertDialog.Builder (Activity);
                takePictureDialog.SetTitle ("Select:");
                takePictureDialog.SetItems (choices.ToArray (), (innerSender, innerE) => {
                    if (innerE.Which == 0) {
                        //gallery
                        mediaPicker.PickPhotoAsync ().ContinueWith (t => {
                            if (t.IsCanceled)
                                return;
                            Activity.RunOnUiThread (() => {
                                photoDialog = new PhotoDialog (Activity);
                                photoDialog.Activity = Activity;
                                photoDialog.Assignment = Assignment;
                                photoDialog.PhotoStream = t.Result.GetStream ();
                                photoDialog.Show ();
                            });
                        });
                    } else if (innerE.Which == 1) {
                        //camera
                        StoreCameraMediaOptions options = new StoreCameraMediaOptions ();
                        options.Directory = "FieldService";
                        options.Name = "FieldService.jpg";
                        mediaPicker.TakePhotoAsync (options).ContinueWith (t => {
                            if (t.IsCanceled)
                                return;
                            Activity.RunOnUiThread (() => {
                                photoDialog = new PhotoDialog (Activity);
                                photoDialog.Activity = Activity;
                                photoDialog.Assignment = Assignment;
                                photoDialog.PhotoStream = t.Result.GetStream ();
                                photoDialog.Show ();
                            });
                        });
                    }
                });
                takePictureDialog.Show ();
            };

            var addSignature = view.FindViewById<Button> (Resource.Id.confirmationsAddSignature);
            if (Assignment != null) {
                addSignature.Enabled = !Assignment.IsHistory;
            }
            addSignature.Click += (sender, e) => {
                signatureDialog = new SignatureDialog (Activity);
                signatureDialog.Activity = Activity;
                signatureDialog.Assignment = Assignment;
                signatureDialog.Show ();
            };

            var completeSignature = view.FindViewById<Button> (Resource.Id.confirmationsComplete);
            if (Assignment != null) {
                completeSignature.Enabled = Assignment.CanComplete;
            }
            completeSignature.Click += (sender, e) => {
                if (assignmentViewModel.Signature == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder (Activity);
                    builder
                        .SetTitle (string.Empty)
                        .SetMessage ("No signature!")
                        .SetPositiveButton ("Ok", (innerSender, innere) => { })
                        .Show ();
                    return;
                }
                completeSignature.Enabled = false;
                Assignment.Status = AssignmentStatus.Complete;
                assignmentViewModel.SaveAssignmentAsync (Assignment)
                    .ContinueWith (_ => {
                        Activity.RunOnUiThread (() => {
                            completeSignature.Enabled = true;
                            Activity.Finish ();
                        });
                    });
            };

            ReloadListView ();

            ReloadSignature ();

            return view;
        }
Exemplo n.º 22
0
        public void OnClick(View v)
        {
            switch (v.Id) {
            case Resource.Id.addExpenseDelete:
                if (CurrentExpense != null && CurrentExpense.Id != -1)
                    DeleteExpense ();
                else
                    Dismiss ();
                break;
            case Resource.Id.addExpenseSave:
                SaveExpense ();
                break;
            case Resource.Id.addExpenseCancel:
                Dismiss ();
                break;
            case Resource.Id.addExpenseAddPhoto:
                var choices = new List<string> ();
                choices.Add (activity.Resources.GetString (Resource.String.Gallery));
                if (mediaPicker.IsCameraAvailable)
                    choices.Add (activity.Resources.GetString (Resource.String.Camera));

                AlertDialog.Builder takePictureDialog = new AlertDialog.Builder (activity);
                takePictureDialog.SetTitle ("Select:");
                takePictureDialog.SetItems (choices.ToArray (), (innerSender, innerE) => {
                    if (innerE.Which == 0) {
                        mediaPicker.PickPhotoAsync ().ContinueWith (t => {
                            if (t.IsCanceled)
                                return;
                            activity.RunOnUiThread (() => {
                                expenseAddPhoto.Visibility = ViewStates.Gone;
                                imageBitmap = BitmapFactory.DecodeStream (t.Result.GetStream ());
                                imageBitmap = Extensions.ResizeBitmap (imageBitmap, Constants.MaxWidth, Constants.MaxHeight);
                                expensePhoto.SetImageBitmap (imageBitmap);
                                expenseViewModel.Photo = new ExpensePhoto { ExpenseId = CurrentExpense.Id };
                            });
                        });
                    } else if (innerE.Which == 1) {
                        //camera
                        StoreCameraMediaOptions options = new StoreCameraMediaOptions ();
                        options.Directory = "FieldService";
                        options.Name = "FieldService.jpg";
                        mediaPicker.TakePhotoAsync (options).ContinueWith (t => {
                            if (t.IsCanceled)
                                return;
                            activity.RunOnUiThread (() => {
                                expenseAddPhoto.Visibility = ViewStates.Gone;
                                imageBitmap = BitmapFactory.DecodeStream (t.Result.GetStream ());
                                imageBitmap = Extensions.ResizeBitmap (imageBitmap, Constants.MaxWidth, Constants.MaxHeight);
                                expensePhoto.SetImageBitmap (imageBitmap);
                                expenseViewModel.Photo = new ExpensePhoto { ExpenseId = CurrentExpense.Id };
                            });
                        });
                    }
                });
                takePictureDialog.Show ();
                break;
            }
        }
Exemplo n.º 23
0
 private void MakePhoto_Click(object sender, EventArgs e)
 {
     var picker = new MediaPicker(Activity);
     if (!picker.IsCameraAvailable || !picker.PhotosSupported)
     {
         ShowUnsupported();
         return;
     }
     var store = new StoreCameraMediaOptions()
     {
         Directory = "Yoursh",
         Name = "photo1.jpg"
     };
     var intent = picker.GetTakePhotoUI(store);
     StartActivityForResult(intent, 2);
 }
Exemplo n.º 24
0
		protected override async void OnResume ()
		{
			base.OnResume ();

			int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0);
			if(itemId > 0) {
				shareItem = App.Database.GetItem(itemId);

				fileName = shareItem.ImagePath;
				Console.WriteLine ("Image path: {0}", fileName);
				Bitmap b = BitmapFactory.DecodeFile (fileName);
				// Display the bitmap
				photoImageView.SetImageBitmap (b);
				locationText.Text = shareItem.Location;
				return;
			}

			if (string.IsNullOrEmpty (fileName)) {
				fileName = "in-progress";
				var picker = new MediaPicker (this);
				if (!picker.IsCameraAvailable) {
					Console.WriteLine ("No camera!");
				} else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString ("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};

					if (!picker.IsCameraAvailable || !picker.PhotosSupported) {
						ShowUnsupported();
						return;
					}

					Intent intent = picker.GetTakePhotoUI (options);

					StartActivityForResult (intent, 1);
				}
			} else {
				SetImage ();
			}

			try {
				var locator = new Geolocator (this) {
					DesiredAccuracy = 50
				};
				var position = await locator.GetPositionAsync (10000);
				Console.WriteLine ("Position Latitude: {0}", position.Latitude);
				Console.WriteLine ("Position Longitude: {0}", position.Longitude);

				location = string.Format ("{0},{1}", position.Latitude, position.Longitude);
				locationText.Text = location;
			} catch (Exception e) {
				Console.WriteLine ("Position Exception: {0}", e.Message);
			}
		}
Exemplo n.º 25
0
		public Task<MediaFile> TakePhotoAsync (StoreCameraMediaOptions options)
		{
			if (!PhotosSupported)
				throw new NotSupportedException();
			if (!IsCameraAvailable)
				throw new NotSupportedException();
			
			VerifyCameraOptions (options);

			return GetMediaAsync (UIImagePickerControllerSourceType.Camera, TypeImage, options);
		}
Exemplo n.º 26
0
      public Task<MediaFile> TakePhotoAsync( StoreCameraMediaOptions options )
      {
         if(!IsCameraAvailable)
         {
            throw new NotSupportedException();
         }

         VerifyOptions( options );

         return TakeMediaAsync( "image/*", MediaStore.ActionImageCapture, options );
      }
Exemplo n.º 27
-1
        public WelcomeViewModel(MediaPicker picker)
        {
            TakeNewPhoto = new ReactiveAsyncCommand();
            ChooseExistingPhoto = new ReactiveAsyncCommand();
            StartEdit = new ReactiveCommand();

            var defaultCamera = new StoreCameraMediaOptions() { DefaultCamera = CameraDevice.Rear, Directory = "LeeMe", Name = "turnt.jpg", };

            Observable.Merge(
                    TakeNewPhoto.RegisterAsyncTask(_ => picker.TakePhotoAsync(defaultCamera)),
                    ChooseExistingPhoto.RegisterAsyncTask(_ => picker.PickPhotoAsync()))
                .Select(x => x.Path)
                .InvokeCommand(StartEdit);

            // TODO: Write a proper UserError handler for this
            TakeNewPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
            ChooseExistingPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
        }