public OperationResult <Stream> GetFirstVideoFrame(string filePath)
        {
            var url            = NSUrl.CreateFileUrl(filePath, false, null);
            var asset          = new AVUrlAsset(url);
            var imageGenerator = new AVAssetImageGenerator(asset);

            imageGenerator.AppliesPreferredTrackTransform = true;

            CMTime  actualTime;
            NSError error;
            var     cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(0, 1), out actualTime, out error);

            if (error != null)
            {
                return(OperationResult <Stream> .AsFailure(error.ToString()));
            }

            if (cgImage != null)
            {
                return(OperationResult <Stream> .AsSuccess(new UIImage(cgImage).AsJPEG().AsStream()));
            }
            else
            {
                return(OperationResult <Stream> .AsFailure("Image generation failed"));
            }
        }
        /// <summary>
        /// Set the device's focus settings
        /// </summary>
        /// <returns><see cref="T:ChilliSource.Mobile.Core.OperationResult"/> instance indicating the outcome of the operation</returns>
        /// <param name="videoDeviceInput">Video device input.</param>
        /// <param name="focusMode">Focus mode.</param>
        /// <param name="exposureMode">Exposure mode.</param>
        /// <param name="pointOfInterest">Point of interest</param>
        /// <param name="monitorSubjectAreaChange">If set to <c>true</c> monitor subject area change.</param>
        public static OperationResult UpdateFocus(this AVCaptureDeviceInput videoDeviceInput, AVCaptureFocusMode focusMode,
                                                  AVCaptureExposureMode exposureMode, CGPoint pointOfInterest, bool monitorSubjectAreaChange)
        {
            if (videoDeviceInput == null)
            {
                return(OperationResult.AsFailure("device input is null"));
            }

            AVCaptureDevice device = videoDeviceInput.Device;
            NSError         error;

            if (device.LockForConfiguration(out error))
            {
                if (device.FocusPointOfInterestSupported && device.IsFocusModeSupported(focusMode))
                {
                    device.FocusPointOfInterest = pointOfInterest;
                    device.FocusMode            = focusMode;
                }
                if (device.ExposurePointOfInterestSupported && device.IsExposureModeSupported(exposureMode))
                {
                    device.ExposurePointOfInterest = pointOfInterest;
                    device.ExposureMode            = exposureMode;
                }
                device.SubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange;
                device.UnlockForConfiguration();
                return(OperationResult.AsSuccess());
            }
            else
            {
                return(OperationResult.AsFailure(string.Format("Could not lock device for configuration: {0}", error)));
            }
        }
        /// <summary>
        /// Invokes <see cref="SearchAsync(string, AutocompleteRequest)"/> with the given <paramref name="autocomleteRequest"/> and caches the results
        /// <param name="input">Search string</param>
        /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param>
        /// </summary>
        public async Task <OperationResult <PlaceResponse> > AutocompleteAsync(string input, AutocompleteRequest autocomleteRequest)
        {
            //Get cached results
            var result = _cachingProvider.GetAutocompleteResult(input);

            if (result != null)
            {
                return(OperationResult <PlaceResponse> .AsSuccess(result));
            }

            var searchResult = await SearchAsync(input, new AutocompleteRequest
            {
                Region = "au"
            })
                               .ContinueWith(response =>
            {
                if (response.Result == null)
                {
                    return(OperationResult <PlaceResponse> .AsFailure("Search response result is null"));
                }
                return(response.Result);
            })
                               .ConfigureAwait(false);

            if (searchResult.IsSuccessful)
            {
                _cachingProvider.StoreAutocompleteResult(input, searchResult.Result);
            }

            return(searchResult);
        }
        public Task <OperationResult <string> > PresentVideoEditor(string videoPath, double maxDuration)
        {
            var tcs = new TaskCompletionSource <OperationResult <string> >();

            var videoEditor = new UIVideoEditorController();

            videoEditor.VideoPath            = videoPath;
            videoEditor.VideoMaximumDuration = maxDuration;
            videoEditor.VideoQuality         = UIImagePickerControllerQualityType.High;
            videoEditor.Failed += (object sender, NSErrorEventArgs e) =>
            {
                videoEditor.DismissModalViewController(true);
                tcs.SetResult(OperationResult <string> .AsFailure(e.Error.LocalizedDescription));
            };
            videoEditor.UserCancelled += (object sender, EventArgs e) =>
            {
                videoEditor.DismissModalViewController(true);
                tcs.SetResult(OperationResult <string> .AsCancel());
            };
            videoEditor.Saved += (object sender, UIPathEventArgs e) =>
            {
                tcs.SetResult(OperationResult <string> .AsSuccess(e.Path));
                videoEditor.DismissModalViewController(true);
            };

            NavigationHelper.GetActiveViewController().PresentViewController(videoEditor, true, null);

            return(tcs.Task);
        }
示例#5
0
        /// <summary>
        /// Sends the API request to generate a list of geo points snapped to a road from the specified <paramref name="positions"/> list of unsnapped points.
        /// <param name="positions">A list of unsnapped geo points</param>
        /// <param name="shouldInterpolate">Determines whether to return additional points to smoothly follow the geometry of the road</param>
        /// <returns>Response model with the snapped positions</returns>
        /// </summary>
        public async Task <OperationResult <RoadsResponse> > RequestSnappedLocations(IList <Position> positions, bool shouldInterpolate)
        {
            if (positions == null || positions.Count == 0)
            {
                return(OperationResult <RoadsResponse> .AsFailure("Please provide at least one position"));
            }

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Content-Type", "application/json;charset=utf-8");


                var fullURLString = RoadsUrlFactory.BuildSnapToRoadsUrl(_apiKey, positions, shouldInterpolate);

                try
                {
                    var responseString = await client.GetStringAsync((fullURLString));

                    return(await ProcessResponse(responseString));
                }
                catch (Exception ex)
                {
                    return(OperationResult <RoadsResponse> .AsFailure("Error communicating with Google Snap To Roads API: " + ex.Message));
                }
            }
        }
        /// <summary>
        /// Invokes places detail webservice to download detail info about a place identified by <paramref name="prediction"/>.PlaceId
        /// <param name="prediction">Search prediction</param>
        /// <returns>The place details</returns>
        /// </summary>
        public Task <OperationResult <DetailsResponse> > GetPlaceDetails(Prediction prediction)
        {
            if (string.IsNullOrWhiteSpace(prediction.PlaceId))
            {
                Task.Run(() =>
                {
                    return(OperationResult <DetailsResponse> .AsFailure("PlaceId cannot be empty"));
                });
            }

            var url = _urlFactory.BuildDetailsUrl(prediction.PlaceId);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Content-Type", "application/json;charset=utf-8");

                return(client.GetStringAsync(url)
                       .ContinueWith(response =>
                {
                    var detailsResult = JsonConvert.DeserializeObject <DetailsResponse>(response.Result);

                    if (detailsResult.Result.Prediction != null)
                    {
                        detailsResult.Result.Prediction = prediction.Description;
                    }
                    return OperationResult <DetailsResponse> .AsSuccess(detailsResult);
                }));
            }
        }
示例#7
0
        /// <summary>
        /// Sends the API request to generate a list of geo points snapped to a road from the specified <paramref name="positions"/> list of unsnapped points.
        /// <param name="positions">A list of unsnapped geo points</param>
        /// <param name="shouldInterpolate">Determines whether to return additional points to smoothly follow the geometry of the road</param>
        /// <returns>Response model with the snapped positions</returns>
        /// </summary>
        public async Task <OperationResult <RoadsResponse> > RequestSnappedLocations(IList <Position> positions, bool shouldInterpolate = false)
        {
            if (positions == null || positions.Count == 0)
            {
                return(OperationResult <RoadsResponse> .AsFailure("Please provide at least one position"));
            }

            using (var client = new HttpClient())
            {
                AcceptJsonResponse(client);
                var fullURLString = RoadsUrlFactory.BuildSnapToRoadsUrl(_apiKey, positions, shouldInterpolate);

                try
                {
                    var response = await client.GetAsync(fullURLString);

                    if (!response.IsSuccessStatusCode)
                    {
                        return(OperationResult <RoadsResponse> .AsFailure(response.ReasonPhrase));
                    }

                    var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    return(await ProcessResponse(content));
                }
                catch (Exception ex)
                {
                    return(OperationResult <RoadsResponse> .AsFailure("Error communicating with Google Snap To Roads API: " + ex.Message));
                }
            }
        }
示例#8
0
        public OperationResult <double> Initialize(string audioFilePath)
        {
            if (string.IsNullOrEmpty(audioFilePath) || !File.Exists(audioFilePath))
            {
                return(OperationResult <double> .AsFailure("Invalid audio file path specified"));
            }

            var audioSession = AVAudioSession.SharedInstance();
            var error        = audioSession.SetCategory(AVAudioSessionCategory.Playback);

            if (error != null)
            {
                return(OperationResult <double> .AsFailure(error.LocalizedDescription));
            }
            error = audioSession.SetActive(true);
            if (error != null)
            {
                return(OperationResult <double> .AsFailure(error.LocalizedDescription));
            }

            NSUrl audioUrl = NSUrl.FromFilename(audioFilePath);

            if (_player != null)
            {
                _player.FinishedPlaying -= DidFinishPlaying;
                _player.Dispose();
                _player = null;
            }

            _player = AVAudioPlayer.FromUrl(audioUrl);
            _player.NumberOfLoops    = 0;
            _player.FinishedPlaying += DidFinishPlaying;

            return(OperationResult <double> .AsSuccess(_player.Duration));
        }
        public OperationResult <double> GetDistanceFrom(Position referencePosition)
        {
            if (referencePosition == null)
            {
                return(OperationResult <double> .AsFailure("Invalid reference position specified"));
            }

            if (_lastPosition == null)
            {
                return(OperationResult <double> .AsFailure("Current position not available"));
            }


            float[] results = new float[1];
            try
            {
                Android.Locations.Location.DistanceBetween(referencePosition.Latitude, referencePosition.Longitude,
                                                           _lastPosition.Latitude, _lastPosition.Longitude, results);
            }
            catch (IllegalArgumentException e)
            {
                return(OperationResult <double> .AsFailure(e));
            }

            if (results != null && results.Length > 0)
            {
                return(OperationResult <double> .AsSuccess(results[0]));
            }
            else
            {
                return(OperationResult <double> .AsFailure("Could not calculate distance"));
            }
        }
        public OperationResult <double> GetDistanceBetween(Position firstPosition, Position secondPosition)
        {
            if (firstPosition == null || secondPosition == null)
            {
                return(OperationResult <double> .AsFailure("Invalid positions specified"));
            }

            float[] results = new float[1];
            try
            {
                Android.Locations.Location.DistanceBetween(firstPosition.Latitude, firstPosition.Longitude,
                                                           secondPosition.Latitude, secondPosition.Longitude, results);
            }
            catch (IllegalArgumentException e)
            {
                return(OperationResult <double> .AsFailure(e));
            }

            if (results != null && results.Length > 0)
            {
                return(OperationResult <double> .AsSuccess(results[0]));
            }
            else
            {
                return(OperationResult <double> .AsFailure("Could not calculate distance"));
            }
        }
        /// <summary>
        /// Start listening to location changes
        /// </summary>
        /// <param name="minTime">Minimum interval in milliseconds</param>
        /// <param name="minDistance">Minimum distance in meters</param>
        /// <param name="includeHeading">Include heading information</param>
        /// <exception cref="System.ArgumentOutOfRangeException">
        ///     minTime
        ///     or
        ///     minDistance
        /// </exception>
        /// <exception cref="System.InvalidOperationException">This Geolocator is already listening</exception>
        public OperationResult StartListening(uint minTime, double minDistance, double desiredAccurancy = 0, bool includeHeading = false)
        {
            if (IsListening)
            {
                return(OperationResult.AsFailure("Already listening"));
            }

            if (minTime < 0)
            {
                return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minTime))));
            }
            if (minDistance < 0)
            {
                return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minDistance))));
            }

            _desiredAccuracy = desiredAccurancy;

            _listener = new GeolocationContinuousListener(_manager, TimeSpan.FromMilliseconds(minTime), _providers);
            _listener.PositionChanged += OnListenerPositionChanged;
            _listener.PositionError   += OnListenerPositionError;

            var looper = Looper.MyLooper() ?? Looper.MainLooper;

            for (var i = 0; i < _providers.Length; ++i)
            {
                _manager.RequestLocationUpdates(_providers[i], minTime, (float)minDistance, _listener, looper);
            }

            return(OperationResult.AsSuccess());
        }
示例#12
0
        public async Task <OperationResult> SnapStillImage()
        {
            AVCaptureConnection connection = _stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
            var previewLayer = (AVCaptureVideoPreviewLayer)PreviewLayer;

            // Update the orientation on the still image output video connection before capturing.
            connection.VideoOrientation = previewLayer.Connection.VideoOrientation;

            // Flash set to Auto for Still Capture.
            _videoDeviceInput.Device.SetFlashMode(AVCaptureFlashMode.Auto);

            // Capture a still image.
            try
            {
                var imageDataSampleBuffer = await _stillImageOutput.CaptureStillImageTaskAsync(connection);

                // The sample buffer is not retained. Create image data before saving the still image to the photo library asynchronously.
                NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(imageDataSampleBuffer);

                if (OnImageSnapped != null)
                {
                    OnImageSnapped(imageData);
                }

                return(OperationResult.AsSuccess());
            }
            catch (NSErrorException ex)
            {
                return(OperationResult.AsFailure(ex));
            }
        }
示例#13
0
        public Task <OperationResult> StartRecording(string filePath)
        {
            TaskCompletionSource <OperationResult> tcs = new TaskCompletionSource <OperationResult>();

            if (_movieFileOutput.Recording)
            {
                tcs.SetResult(OperationResult.AsFailure("Recording already in progress"));
            }
            else
            {
                if (UIDevice.CurrentDevice.IsMultitaskingSupported)
                {
                    // Setup background task. This is needed because the IAVCaptureFileOutputRecordingDelegate.FinishedRecording
                    // callback is not received until AVCam returns to the foreground unless you request background execution time.
                    // This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
                    // To conclude this background execution, UIApplication.SharedApplication.EndBackgroundTask is called in
                    // IAVCaptureFileOutputRecordingDelegate.FinishedRecording after the recorded file has been saved.
                    _backgroundRecordingID = UIApplication.SharedApplication.BeginBackgroundTask(null);
                }

                // Update the orientation on the movie file output video connection before starting recording.
                AVCaptureConnection connection = _movieFileOutput.ConnectionFromMediaType(AVMediaType.Video);
                connection.VideoOrientation = PreviewLayer.Connection.VideoOrientation;

                // Turn OFF flash for video recording.
                _videoDeviceInput.Device.SetFlashMode(AVCaptureFlashMode.Off);

                // Start recording to a temporary file.
                _movieFileOutput.StartRecordingToOutputFile(new NSUrl(filePath, false), this);

                tcs.SetResult(OperationResult.AsSuccess());
            }

            return(tcs.Task);
        }
        public Task <OperationResult <string> > FetchDeferredAppLink()
        {
            var tcs = new TaskCompletionSource <OperationResult <string> >();

            AppLinkUtility.FetchDeferredAppLink((url, error) =>
            {
                if (error != null)
                {
                    tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription));
                }
                else
                {
                    if (url == null)
                    {
                        tcs.SetResult(OperationResult <string> .AsFailure("Returned Url is null"));
                    }
                    else
                    {
                        tcs.SetResult(OperationResult <string> .AsSuccess(url.ToString()));
                    }
                }
            });

            return(tcs.Task);
        }
        public OperationResult <byte[]> ResizeImage(string sourcePath, float maxWidth, float maxHeight)
        {
            if (!File.Exists(sourcePath))
            {
                return(OperationResult <byte[]> .AsFailure("Source file not found"));
            }

            var extension = Path.GetExtension(sourcePath).ToLower();

            UIImage sourceImage = UIImage.FromFile(sourcePath);
            var     resultImage = sourceImage.Resize(maxWidth, maxHeight);

            if (extension.Contains("png"))
            {
                return(OperationResult <byte[]> .AsSuccess(resultImage.AsPNG().ToArray()));
            }
            else if (extension.Contains("jpg") || extension.Contains("jpeg"))
            {
                return(OperationResult <byte[]> .AsSuccess(resultImage.AsJPEG().ToArray()));
            }
            else
            {
                return(OperationResult <byte[]> .AsFailure("Extension not supported"));
            }
        }
        public Task <OperationResult> PerformBiometricAuthentication(string promptText)
        {
            var tcs = new TaskCompletionSource <OperationResult>();

            var     context = new LAContext();
            NSError authError;
            var     message = new NSString(promptText);

            if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError))
            {
                var replyHandler = new LAContextReplyHandler((success, error) =>
                {
                    if (success)
                    {
                        tcs.SetResult(OperationResult.AsSuccess());
                    }
                    else
                    {
                        tcs.SetResult(OperationResult.AsFailure((error as NSError).LocalizedDescription));
                    }
                });

                // This starts the authentication dialog.
                context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, message, replyHandler);
            }
            return(tcs.Task);
        }
示例#17
0
        public Task <OperationResult <string> > SaveVideo(string videoPath)
        {
            var tcs = new TaskCompletionSource <OperationResult <string> >();

            if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath))
            {
                tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified"));
                return(tcs.Task);
            }

            var url = NSUrl.CreateFileUrl(videoPath, false, null);

            string localId = string.Empty;

            PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
            {
                var request = PHAssetChangeRequest.FromVideo(url);
                localId     = request?.PlaceholderForCreatedAsset?.LocalIdentifier;
            }, (bool success, NSError error) =>
            {
                if (!success && error != null)
                {
                    tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription));
                }
                else
                {
                    tcs.SetResult(OperationResult <string> .AsSuccess(localId));
                }
            });

            return(tcs.Task);
        }
示例#18
0
        /// <summary>
        /// Sets the device's frame rate
        /// </summary>
        /// <returns><see cref="T:ChilliSource.Mobile.Core.OperationResult"/> instance indicating the outcome of the operation</returns>
        /// <param name="device">Device.</param>
        /// <param name="frameRate">Frame rate.</param>
        /// <param name="timeValue">Time value.</param>
        public static OperationResult SetFrameRate(this AVCaptureDevice device, int frameRate, int timeValue = 1)
        {
            NSError error = null;

            if (!device.LockForConfiguration(out error))
            {
                return(OperationResult.AsFailure(error?.LocalizedDescription ?? "Could not lock configuration"));
            }

            double epsilon = 0.00000001;

            bool frameRateSet = false;

            foreach (var range in device.ActiveFormat.VideoSupportedFrameRateRanges)
            {
                if (range.MinFrameRate <= frameRate + epsilon && range.MaxFrameRate >= frameRate - epsilon)
                {
                    device.ActiveVideoMaxFrameDuration = new CoreMedia.CMTime(timeValue, frameRate);
                    device.ActiveVideoMinFrameDuration = new CoreMedia.CMTime(timeValue, frameRate);
                    frameRateSet = true;
                    break;
                }
            }

            device.UnlockForConfiguration();
            return(frameRateSet ? OperationResult.AsSuccess() : OperationResult.AsFailure("Frame rate is not supported"));
        }
示例#19
0
        //needed for sharing to Facebook
        public Task <OperationResult <string> > LegacySaveVideo(string videoPath)
        {
            var tcs = new TaskCompletionSource <OperationResult <string> >();

            if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath))
            {
                tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified"));
                return(tcs.Task);
            }


            var url     = NSUrl.CreateFileUrl(videoPath, false, null);
            var library = new ALAssetsLibrary();

            library.WriteVideoToSavedPhotosAlbum(url, (resultUrl, error) =>
            {
                if (error == null)
                {
                    tcs.SetResult(OperationResult <string> .AsSuccess(resultUrl.AbsoluteString));
                }
                else
                {
                    tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription));
                }
            });

            return(tcs.Task);
        }
        /// <summary>
        /// Invokes <see cref="SearchAsync(string, AutocompleteRequest)"/> with the given <paramref name="autocomleteRequest"/> and caches the results
        /// <param name="input">Search string</param>
        /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param>
        /// </summary>
        public async Task <OperationResult <PlaceResponse> > AutocompleteAsync(string input, AutocompleteRequest autocomleteRequest = null)
        {
            //Get cached results
            var result = _cachingProvider.GetAutocompleteResult(input);

            if (result != null)
            {
                return(OperationResult <PlaceResponse> .AsSuccess(result));
            }

            OperationResult <PlaceResponse> searchResult;

            if (autocomleteRequest != null)
            {
                searchResult = await SearchAsync(input, autocomleteRequest);
            }
            else
            {
                searchResult = await SearchAsync(input, new AutocompleteRequest()
                {
                    Region = "au"
                });
            }


            if (!searchResult.IsSuccessful)
            {
                return(OperationResult <PlaceResponse> .AsFailure("Search response result is null"));
            }

            _cachingProvider.StoreAutocompleteResult(input, searchResult.Result);

            return(searchResult);
        }
示例#21
0
        private Task <OperationResult <LibraryMediaItem> > GetLastSavedMediaItem(MediaItemType itemType)
        {
            var tcs = new TaskCompletionSource <OperationResult <LibraryMediaItem> >();

            var fetchOptions = new PHFetchOptions();

            fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };
            var fetchResult = PHAsset.FetchAssets(itemType == MediaItemType.Video ? PHAssetMediaType.Video : PHAssetMediaType.Image, fetchOptions);
            var phAsset     = fetchResult?.firstObject as PHAsset;

            if (phAsset != null)
            {
                PHImageManager.DefaultManager.RequestAvAsset(phAsset, null, (asset, audioMix, info) =>
                {
                    var urlAsset = asset as AVUrlAsset;
                    tcs.SetResult(OperationResult <LibraryMediaItem> .AsSuccess(new LibraryMediaItem(phAsset.LocalIdentifier, urlAsset.Url.AbsoluteString)));
                });
            }
            else
            {
                tcs.SetResult(OperationResult <LibraryMediaItem> .AsFailure("Could not retrieve last asset"));
            }

            return(tcs.Task);
        }
        /// <summary>
        /// Invokes places detail webservice to download detail info about a place identified by <paramref name="prediction"/>.PlaceId
        /// <param name="prediction">Search prediction</param>
        /// <returns>The place details</returns>
        /// </summary>
        public async Task <OperationResult <DetailsResponse> > GetPlaceDetails(Prediction prediction)
        {
            if (string.IsNullOrWhiteSpace(prediction.PlaceId))
            {
                return(OperationResult <DetailsResponse> .AsFailure("PlaceId cannot be empty"));
            }

            var url = _urlFactory.BuildDetailsUrl(prediction.PlaceId);

            using (var client = new HttpClient())
            {
                AcceptJsonResponse(client);

                var response = await client.GetAsync(url).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    return(OperationResult <DetailsResponse> .AsFailure(response.ReasonPhrase));
                }

                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var detailsResult = JsonConvert.DeserializeObject <DetailsResponse>(content);

                if (detailsResult.Status == GoogleApiResponseStatus.Ok && detailsResult.Result.Prediction != null)
                {
                    detailsResult.Result.Prediction = prediction.Description;
                }


                return(OperationResult <DetailsResponse> .AsSuccess(detailsResult));
            }
        }
        /// <summary>
        /// Invokes places search webservice
        /// <param name="searchString">Search string</param>
        /// <param name="request">Autocomplete request specifying additional components in the search Url to be generated</param>
        /// <returns>Place result with predictions</returns>
        /// </summary>
        public async Task <OperationResult <PlaceResponse> > SearchAsync(string searchString, AutocompleteRequest request)
        {
            if (string.IsNullOrWhiteSpace(searchString))
            {
                return(OperationResult <PlaceResponse> .AsFailure("PlaceId cannot be empty"));
            }

            var url = _urlFactory.BuildSearchUrl(searchString, request);

            using (var client = new HttpClient())
            {
                AcceptJsonResponse(client);

                var response = await client.GetAsync(url).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    return(OperationResult <PlaceResponse> .AsFailure(response.ReasonPhrase));
                }

                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var result = JsonConvert.DeserializeObject <PlaceResponse>(content);
                return(OperationResult <PlaceResponse> .AsSuccess(result));
            }
        }
        public OperationResult Initialize(string audioFilePath, float sampleRate = 44100, int channels = 2, int bitDepth = 16)
        {
            if (string.IsNullOrEmpty(audioFilePath))
            {
                return(OperationResult <double> .AsFailure("Invalid audio file path specified"));
            }

            _audioFilePath = audioFilePath;

            if (_recorder == null)
            {
                _recorder = new MediaRecorder();
                _recorder.SetAudioSource(AudioSource.Mic);
                _recorder.SetOutputFormat(OutputFormat.ThreeGpp);
                _recorder.SetAudioEncoder(AudioEncoder.AmrNb);
            }
            else
            {
                if (File.Exists(_audioFilePath))
                {
                    File.Delete(_audioFilePath);
                }
            }

            File.Create(audioFilePath);
            _recorder.SetOutputFile(audioFilePath);
            _recorder.Prepare();

            return(OperationResult.AsSuccess());
        }
 public override void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status)
 {
     // If user has services disabled, we're just going to throw an exception for consistency.
     if (status == CLAuthorizationStatus.Denied || status == CLAuthorizationStatus.Restricted)
     {
         StopListening();
         _tcs.SetResult(OperationResult <Position> .AsFailure(new LocationException(LocationErrorType.Unauthorized)));
     }
 }
示例#26
0
        private Task <OperationResult> GetMediaItem(string destinationPath, MediaItemType mediaItemType, UIImagePickerControllerSourceType sourceType)
        {
            var tcs = new TaskCompletionSource <OperationResult>();

            var picker = new ExtendedUIImagePickerController();

            picker.PreferredOrientation = UIApplication.SharedApplication.StatusBarOrientation;
            if (mediaItemType == MediaItemType.Video)
            {
                picker.VideoQuality = UIImagePickerControllerQualityType.At1280x720;
            }
            picker.SourceType = sourceType;
            var typeString = mediaItemType == MediaItemType.Video ? "public.movie" : "public.image";

            picker.MediaTypes = new string[] { typeString };

            picker.Canceled += (object sender, EventArgs e) =>
            {
                tcs.SetResult(OperationResult.AsCancel());
                picker.DismissViewController(true, null);
            };
            picker.FinishedPickingMedia += (object sender, UIImagePickerMediaPickedEventArgs e) =>
            {
                picker.DismissViewController(true, () =>
                {
                    NSUrl mediaURl = null;

                    if (e.MediaUrl != null)
                    {
                        mediaURl = e.MediaUrl;
                        File.Copy(mediaURl.Path, destinationPath, true);
                        tcs.SetResult(OperationResult.AsSuccess());
                    }
                    else
                    {
                        var originalImage = e.OriginalImage;
                        var imageData     = originalImage.AsJPEG();

                        NSError err = null;

                        if (imageData.Save(destinationPath, false, out err))
                        {
                            tcs.SetResult(OperationResult.AsSuccess());
                        }
                        else
                        {
                            tcs.SetResult(OperationResult.AsFailure(err.LocalizedDescription));
                        }
                    }
                });
            };

            NavigationHelper.GetActiveViewController().PresentViewController(picker, true, null);

            return(tcs.Task);
        }
        public void Combine_ShouldFail_WhenResultConsistsAtLeastOneErrorResult()
        {
            var res1 = OperationResult.AsFailure("failed");
            var res2 = OperationResult.AsSuccess();
            var res3 = OperationResult.AsFailure("test");

            var r = OperationResult.Combine(res1, res2, res3);

            Assert.False(r.IsSuccessful);
            Assert.True(r.Message.Contains("failed"));
        }
示例#28
0
        public OperationResult <double> GetDistanceBetween(Position firstPosition, Position secondPosition)
        {
            if (firstPosition == null || secondPosition == null)
            {
                return(OperationResult <double> .AsFailure("Invalid positions specified"));
            }

            var firstLocation  = new CLLocation(firstPosition.Latitude, firstPosition.Longitude);
            var secondLocation = new CLLocation(secondPosition.Latitude, secondPosition.Longitude);

            return(OperationResult <double> .AsSuccess(firstLocation.DistanceFrom(secondLocation)));
        }
 public override void Failed(CLLocationManager manager, NSError error)
 {
     switch ((CLError)(int)error.Code)
     {
     case CLError.Network:
     {
         StopListening();
         _tcs.SetResult(OperationResult <Position> .AsFailure((new LocationException(LocationErrorType.PositionUnavailable))));
         break;
     }
     }
 }
示例#30
0
        public OperationResult StartCapture()
        {
            if (_setupResult != CameraSetupResult.Success)
            {
                return(OperationResult.AsFailure("Setup has not completed successfully"));
            }

            if (!_session.Running)
            {
                _session.StartRunning();
            }
            return(OperationResult.AsSuccess());
        }