Ejemplo n.º 1
0
        private void OnUserLoad(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var userData = ServiceContainer.Resolve <AuthManager> ().User;

            if (userData == null)
            {
                return;
            }

            usernameLabel.Text = userData.Name;
            emailLabel.Text    = userData.Email;

            UIImage image;

            // Try to download the image from server
            // if user doesn't have image configured or
            // there is not connection, use a local image.
            try {
                var url  = new NSUrl(userData.ImageUrl);
                var data = NSData.FromUrl(url);
                image = UIImage.LoadFromData(data);
            } catch (Exception ex) {
                image = UIImage.FromFile("profile.png");
            }
            userAvatarImage.Image = image;
        }
Ejemplo n.º 2
0
        private static UIFont GetFontFromFile(nfloat size, string file)
        {
            var fileName      = Path.GetFileNameWithoutExtension(file);
            var fileExtension = Path.GetExtension(file)?.Replace(".", "");

            var url = NSBundle
                      .MainBundle
                      .GetUrlForResource(
                name: fileName,
                fileExtension: fileExtension,
                subdirectory: "Fonts"
                );

            if (url == null)
            {
                return(null);
            }

            var fontData = NSData.FromUrl(url);

            if (fontData == null)
            {
                return(null);
            }

            //iOS loads UIFonts based on the PostScriptName of the font file
            using (var fontProvider = new CGDataProvider(fontData))
            {
                using (var font = CGFont.CreateFromProvider(fontProvider))
                {
                    return(font != null?UIFont.FromName(font.PostScriptName, size) : null);
                }
            }
        }
Ejemplo n.º 3
0
        private async void GoogleAuth_Completed(object sender, AuthenticatorCompletedEventArgs e)
        {
            // We presented the UI, so it's up to us to dimiss it on iOS.
            DismissViewController(true, null);

            if (e.IsAuthenticated)
            {
                var account  = e.Account;
                var request  = new OAuth2Request("GET", new Uri(UserInfoUrl), null, account);
                var response = await request.GetResponseAsync();

                if (response != null)
                {
                    string userJson = response.GetResponseText();
                    var    user     = JsonConvert.DeserializeObject <UserDetailsGoogleDto>(userJson);
                    LblName.Text = user.Name;
                    //IdLabel.Text += id;
                    LblDescription.Text = user.Email;
                    ImgVUser.Image      = UIImage.LoadFromData(NSData.FromUrl(new NSUrl(user.Picture)));
                }
            }
            else
            {
                // The user cancelled
            }
        }
Ejemplo n.º 4
0
        private void DownloadUsingPlatformDownloader()
        {
            using (var url = new NSUrl(WebUri.OriginalString))
            {
                NSError error;

                if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                {
                    this.Log().Debug($"Loading image from [{WebUri.OriginalString}]");
                }

                // fallback on the platform's loader
                using (var data = NSData.FromUrl(url, NSDataReadingOptions.Coordinated, out error))
                {
                    if (error != null)
                    {
                        this.Log().Error(error.LocalizedDescription);
                    }
                    else
                    {
                        ImageData = new NSImage(data);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void ProvideData(NSPasteboard pboard, NSString type)
        {
            NSData data;
            var    obj = DataSource();

            if (obj is Xwt.Drawing.Image)
            {
                var bmp = ((Xwt.Drawing.Image)obj).ToBitmap();
                data = ((NSImage)Toolkit.GetBackend(bmp)).AsTiff();
            }
            else if (obj is NSImage)
            {
                data = ((NSImage)obj).AsTiff();
            }
            else if (obj is Uri)
            {
                data = NSData.FromUrl((NSUrl)((Uri)obj));
            }
            else if (obj is string)
            {
                data = NSData.FromString((string)obj);
            }
            else
            {
                data = NSData.FromArray(TransferDataSource.SerializeValue(obj));
            }
            pboard.SetDataForType(data, type);
        }
Ejemplo n.º 6
0
        public Task <string> RecordVideo()
        {
            var task = new TaskCompletionSource <string>();

            try
            {
                Services.Media.RecordVideo(GetController(), (data) =>
                {
                    if (data == null)
                    {
                        task.SetResult(null);
                        return;
                    }

                    //check for camera
                    var mediaUrl         = data.ValueForKey(new NSString("UIImagePickerControllerMediaURL")) as NSUrl;
                    var videoData        = NSData.FromUrl(NSUrl.FromString(mediaUrl.ToString()));
                    string videoFilename = Path.Combine(GetVideoDirectoryPath(), GetUniqueFileName(".mp4"));
                    NSError err          = null;
                    if (videoData.Save(videoFilename, false, out err))
                    {
                        task.SetResult(videoFilename);
                    }
                    else
                    {
                        task.SetResult(null);
                    }
                });
            }
            catch (Exception ex)
            {
                task.SetException(ex);
            }
            return(task.Task);
        }
        private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
        {
            var securityEnabled = e.Url.StartAccessingSecurityScopedResource();
            var doc             = new UIDocument(e.Url);
            var data            = NSData.FromUrl(e.Url);
            var dataBytes       = new byte [data.Length];

            System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

            string filename = doc.LocalizedName;
            string pathname = doc.FileUrl?.ToString();

            // iCloud drive can return null for LocalizedName.
            if (filename == null)
            {
                // Retrieve actual filename by taking the last entry after / in FileURL.
                // e.g. /path/to/file.ext -> file.ext

                // filesplit is either:
                // 0 (pathname is null, or last / is at position 0)
                // -1 (no / in pathname)
                // positive int (last occurence of / in string)
                var filesplit = pathname?.LastIndexOf('/') ?? 0;

                filename = pathname?.Substring(filesplit + 1);
            }

            OnFilePicked(new FilePickerEventArgs(dataBytes, filename, pathname));
        }
Ejemplo n.º 8
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();
            UserName.Text = AppSettingsManager.FirstName + " " + AppSettingsManager.LastName;

            using (var url = new NSUrl(AppSettingsManager.ProfilePictureUrl))
                using (var data = NSData.FromUrl(url))
                {
                    ProfilePictureImageView.Image = UIImage.LoadFromData(data);
                }

            LikeButton.TouchUpInside += (sender, args) => {
                CurrentPhoto.IsLiked = !CurrentPhoto.IsLiked;
                LikeButton.SetTitleColor(CurrentPhoto.IsLiked ? UIColor.Red : UIColor.Blue, UIControlState.Normal);
            };

            //DeleteButton.TouchUpInside += ( sender, args ) => {
            //    CurrentPhoto.ToBeDeleted = true;
            //    //ContentView.Hidden = true;

            //    //ContentView.Frame = CGRect.Empty;
            //    //Frame = CGRect.Empty;


            //    //_table.ReloadRows(new[] { _path}, UITableViewRowAnimation.Fade );
            //    _table.Delete(null);
            //    PhotoDataSource.Source.RemoveAtIndex(_path);
            //    _table.DeleteRows(new [] {_path}, UITableViewRowAnimation.Automatic );
            //};
        }
Ejemplo n.º 9
0
 public void Https()
 {
     using (var url = new NSUrl("https://blog.xamarin.com/robots.txt"))
         using (var x = NSData.FromUrl(url)) {
             Assert.That((x != null) && (x.Length > 0));
         }
 }
Ejemplo n.º 10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Get the item[s] we're handling from the extension context.

            // For example, look for an image and place it into an image view.
            // Replace this with something appropriate for the type[s] your extension supports.
            bool imageFound = false;

            foreach (var item in ExtensionContext.InputItems)
            {
                foreach (var itemProvider in item.Attachments)
                {
                    if (itemProvider.HasItemConformingTo(UTType.URL))
                    {
                        itemProvider.LoadItem(UTType.URL, null, delegate(NSObject url, NSError error)
                        {
                            NSOperationQueue.MainQueue.AddOperation(delegate
                            {
                                var nsUrl  = url as NSUrl;
                                _rawData   = nsUrl.AbsoluteString;
                                _mediaType = "text/plain";
                            });
                        });

                        imageFound = true;
                        break;
                    }
                    else if (itemProvider.HasItemConformingTo(UTType.Image))
                    {
                        // This is an image. We'll load it, then place it in our image view.
                        itemProvider.LoadItem(UTType.Image, null, delegate(NSObject image, NSError error)
                        {
                            var url = image as NSUrl;
                            if (url != null)
                            {
                                NSOperationQueue.MainQueue.AddOperation(delegate
                                {
                                    // Get encoded data.
                                    var data     = UIImage.LoadFromData(NSData.FromUrl(url)).AsJPEG(1.0f);
                                    var str      = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
                                    _encodedData = str;
                                    _mediaType   = "image/jpeg";
                                });
                            }
                        });

                        imageFound = true;
                        break;
                    }
                }

                if (imageFound)
                {
                    // We only handle one image, so stop looking for more.
                    break;
                }
            }
        }
        public Result <LoadedItem <T> > Load(Item <T> item)
        {
            T resultObject = default(T);
            NSFileAttributes attributes = null;

            attributes = _fileManager.GetAttributes(item.Url.Path);

            if (item.Type == ItemType.Directory)
            {
                NSString[] properties = new[] { NSUrl.IsDirectoryKey, NSUrl.ContentModificationDateKey };
                NSError    error      = null;
                var        urls       = _fileManager.GetDirectoryContent(item.Url, NSArray.FromNSObjects(properties),
                                                                         NSDirectoryEnumerationOptions.SkipsHiddenFiles,
                                                                         out error);

                resultObject = item.Parse(attributes, null, urls);
            }
            else
            {
                var data = NSData.FromUrl(item.Url);
                resultObject = item.Parse(attributes, data, null);
            }

            return(new Result <LoadedItem <T> >(new LoadedItem <T>(item, attributes, resultObject)));
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var reusableCell = tableView.DequeueReusableCell("sampleCell");

            if (reusableCell == null)
            {
                reusableCell = new UITableViewCell(UITableViewCellStyle.Default, "sampleCell");
                reusableCell.TextLabel.Font = reusableCell.TextLabel.Font.WithSize(12);
            }

            var book = Source[indexPath.Row];

            reusableCell.TextLabel.Text = book.Title;

            var mainScale = (float)UIScreen.MainScreen.Scale;

            Task.Run(() =>
            {
                System.Diagnostics.Debug.WriteLine("In get image:" + book.Thumbnail);
                using var url  = NSUrl.FromString(book.Thumbnail);
                using var data = NSData.FromUrl(url);
                var image      = UIImage.LoadFromData(data);
                System.Diagnostics.Debug.WriteLine(image);
                image = image.Scale(new CGSize(30, 40), mainScale);
                BeginInvokeOnMainThread(() =>
                {
                    reusableCell.ImageView.Image = image;
                    reusableCell.SetNeedsLayout();
                });
            });

            return(reusableCell);
        }
        public void Load(FoodMarker marker)
        {
            nfloat imageHeight = 130;
            var    imageMeta   = marker.FoodMarkerPhotos.Where(p => p.ImageRank == 1).First();

            if (marker.FoodMarkerPhotos.Where(p => p.ImageRank == 2).Any())
            {
                imageMeta = marker.FoodMarkerPhotos.Where(p => p.ImageRank == 2).First();
            }

            UIImage uiImage;

            using (var url = new NSUrl(imageMeta.ImageUrl))
            {
                using (var data = NSData.FromUrl(url))
                {
                    uiImage = UIImage.LoadFromData(data);
                }
            }
            _image.Image = uiImage;

            _image.Frame = new CGRect(
                0,
                5f,
                ControlProps.Width,
                imageHeight
                );
            _image.ContentMode        = UIViewContentMode.ScaleAspectFill;
            _image.Center             = new CGPoint(ContainingView.Center.X, _image.Center.Y);
            _image.ClipsToBounds      = true;
            _image.Layer.CornerRadius = 15f;


            Configuration.TintColor = UIColor.Yellow;
            var gallery = new AlbumViewController()
            {
                LazyDataSource = (view, size, mediaTypes) =>
                                 new LocalFilesDataSource(view, size, mediaTypes)
                {
                    ImagesPath = (new FoodMarkerImageDirectory()).GetDir()
                },
                LazyDelegate = (view, source) => new LocalFilesDelegate(view, (LocalFilesDataSource)source)
            };

            var gestureRec = new UITapGestureRecognizer(() =>
            {
                _controller.PresentViewController(gallery, true, null);
            });

            gestureRec.CancelsTouchesInView = false;
            _image.AddGestureRecognizer(gestureRec);
            _image.UserInteractionEnabled = true;

            View.Frame = new CGRect(
                0,
                _parentContainer.View.Frame.GetMaxY(),
                ContainingView.Frame.Width,
                imageHeight + 10f
                );
        }
Ejemplo n.º 14
0
		public Sound(string url, float volume, bool looping)
		{			
			var data = NSData.FromUrl(NSUrl.FromFilename(url));
			_audioPlayer = new NSSound(data);
			_audioPlayer.Volume = volume;
			_audioPlayer.Loops = looping;
		}
        protected async void LoadImageInBackground(UIImageView imageView, string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                imageView.Image = PlaceHolder;
                return;
            }
            UIImage image;

            imageView.Tag = url.GetHashCode();
            if (!_cache.TryGetValue(url, out image))
            {
                imageView.Image = PlaceHolder;
                try
                {
                    image = await Task.Run(() => new UIImage(NSData.FromUrl(new NSUrl(url))));

                    _cache[url] = image;
                }
                catch { }
            }
            if (imageView.Tag == url.GetHashCode() && image != null)
            {
                imageView.Image = image;
            }
        }
Ejemplo n.º 16
0
        public static UIImage GetProfileImageforUser(int userid)
        {
            //String usid =Convert.ToString(CurrentUser.RetreiveUserId());
            //NSObject pro = ProfileImages.ObjectForKey(NSObject.FromObject(usid));

            //NSObject profile = profilePics.ObjectForKey(NSObject.FromObject(userid));

            //if (profile != null)
            //	return (UIImage)profile;

            NSData  imgData = null;
            UIImage img     = null;

            try
            {
                url = "https://icsintegration.blob.core.windows.net/profileimages/" + userid + ".jpg";
                NSUrl imageURL = new NSUrl(url);
                imgData = NSData.FromUrl(imageURL);
                img     = UIImage.LoadFromData(imgData);
                profilePics.SetObjectforKey(img, NSObject.FromObject(userid));
            }
            catch (Exception e)
            {
                //LoggingClass.LogError(e.ToString(), screen, e.StackTrace);

                return(null);
            }

            return(img);
        }
        /// <summary>
        /// Purchase a specific product or subscription
        /// </summary>
        /// <param name="productId">Sku or ID of product</param>
        /// <param name="itemType">Type of product being requested</param>
        /// <param name="payload">Developer specific payload</param>
        /// <param name="verifyPurchase">Interface to verify purchase</param>
        /// <returns></returns>
        public async Task <InAppBillingPurchase> PurchaseAsync(string productId, ItemType itemType, string payload, IInAppBillingVerifyPurchase verifyPurchase = null)
        {
            var p = await PurchaseAsync(productId);

            var reference = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

            var purchase = new InAppBillingPurchase
            {
                TransactionDateUtc = reference.AddSeconds(p.TransactionDate.SecondsSinceReferenceDate),
                Id        = p.TransactionIdentifier,
                ProductId = p.Payment?.ProductIdentifier ?? string.Empty,
                State     = p.GetPurchaseState()
            };

            if (verifyPurchase == null)
            {
                return(purchase);
            }

            // Get the receipt data for (server-side) validation.
            // See: https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Introduction.html#//apple_ref/doc/uid/TP40010573
            var    receiptUrl = NSData.FromUrl(NSBundle.MainBundle.AppStoreReceiptUrl);
            string receipt    = receiptUrl.GetBase64EncodedString(NSDataBase64EncodingOptions.None);

            var validated = await verifyPurchase.VerifyPurchase(receipt, string.Empty);


            return(validated ? purchase : null);
        }
Ejemplo n.º 18
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            if (_product.IsFavorite)
            {
                favoriteButton.Image = UIImage.FromBundle("full_star");
            }
            else
            {
                favoriteButton.Image = UIImage.FromBundle("empty_star");
            }

            productNameLabel.Text        = _product.Name;
            productDescriptionLabel.Text = _product.Description;
            productPriceLabel.Text       = string.Format("R$ {0:0.00}", _product.Price);

            var url  = new NSUrl(_product.PhotoUrl);
            var data = NSData.FromUrl(url);

            if (data != null)
            {
                productPhotoImageView.Image = new UIImage(data);
            }
        }
Ejemplo n.º 19
0
        public Task <bool> CompressVideo(string inputPath, string outputPath)
        {
            var      task          = new TaskCompletionSource <bool>();
            NSString urlString     = new NSString(inputPath);
            NSUrl    myFileUrl     = new NSUrl(urlString);
            var      export        = new AVAssetExportSession(AVAsset.FromUrl(myFileUrl), AVAssetExportSession.PresetMediumQuality);
            string   videoFilename = outputPath;

            export.OutputUrl      = NSUrl.FromFilename(videoFilename);
            export.OutputFileType = AVFileType.Mpeg4;
            export.ShouldOptimizeForNetworkUse = true;

            export.ExportAsynchronously(() =>
            {
                if (export.Status == AVAssetExportSessionStatus.Completed)
                {
                    var videoData = NSData.FromUrl(NSUrl.FromString(export.OutputUrl.ToString()));
                    NSError err   = null;
                    if (videoData.Save(videoFilename, false, out err))
                    {
                        task.SetResult(true);
                    }
                    else
                    {
                        task.SetResult(true);
                    }
                }
                else
                {
                    task.SetResult(false);
                }
            });

            return(task.Task);
        }
Ejemplo n.º 20
0
        private void DownloadUsingPlatformDownloader()
        {
            using (var url = new NSUrl(WebUri.AbsoluteUri))
            {
                NSError error;

                if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug))
                {
                    this.Log().Debug($"Loading image from [{WebUri.OriginalString}]");
                }

#pragma warning disable CS0618
                // fallback on the platform's loader
                using (var data = NSData.FromUrl(url, NSDataReadingOptions.Mapped, out error))
#pragma warning restore CS0618
                {
                    if (error != null)
                    {
                        this.Log().Error(error.LocalizedDescription);
                    }
                    else
                    {
                        ImageData = new NSImage(data);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public override void ShareFileAsync(string path, string subject, string mimeType)
        {
            SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
            {
                if (!MFMailComposeViewController.CanSendMail)
                {
                    FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
                    return;
                }

                NSData data = NSData.FromUrl(NSUrl.FromFilename(path));

                if (data == null)
                {
                    FlashNotificationAsync("No file to share.");
                    return;
                }

                MFMailComposeViewController mailer = new MFMailComposeViewController();
                mailer.SetSubject(subject);
                mailer.AddAttachmentData(data, mimeType, Path.GetFileName(path));
                mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
            });
        }
Ejemplo n.º 22
0
 public static KeyValuePair <NSString, NSObject> ToUiPasteboardItem(this IMimeItem mimeItem)
 {
     if (mimeItem.MimeType?.ToNsUti() is NSString nsUti) // && mimeItem.Value.ToNSObject() is NSObject nSObject)
     {
         NSData nsData = null;
         if (mimeItem.Value is byte[] byteArray)
         {
             nsData = NSData.FromArray(byteArray);
         }
         else if (mimeItem.Value is FileInfo fileInfo)
         {
             nsData = NSData.FromFile(fileInfo.FullName);
         }
         else if (mimeItem.Value is Uri uri)
         {
             var nsUrl = new NSUrl(uri.AbsoluteUri);
             nsData = NSData.FromUrl(nsUrl);
         }
         if (mimeItem.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase) && nsData != null && nsData.Length > 0)
         {
             var uiImage = UIImage.LoadFromData(nsData);
             return(new KeyValuePair <NSString, NSObject>(nsUti, uiImage));
         }
         NSObject nsObject = nsData ?? mimeItem.Value.ToNSObject();
         if (nsObject != null)
         {
             return(new KeyValuePair <NSString, NSObject>(nsUti, nsObject));
         }
     }
     return(new KeyValuePair <NSString, NSObject>());
 }
Ejemplo n.º 23
0
        private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
        {
            e.Url.StartAccessingSecurityScopedResource();

            var doc      = new UIDocument(e.Url);
            var fileName = doc.LocalizedName;

            if (string.IsNullOrWhiteSpace(fileName))
            {
                var path = doc.FileUrl?.ToString();
                if (path != null)
                {
                    path = WebUtility.UrlDecode(path);
                    var split = path.LastIndexOf('/');
                    fileName = path.Substring(split + 1);
                }
            }

            var     fileCoordinator = new NSFileCoordinator();
            NSError error;

            fileCoordinator.CoordinateRead(e.Url, NSFileCoordinatorReadingOptions.WithoutChanges, out error, (url) =>
            {
                var data = NSData.FromUrl(url).ToArray();
                SelectFileResult(data, fileName ?? "unknown_file_name");
            });

            e.Url.StopAccessingSecurityScopedResource();
        }
        public void Init()
        {
            TestRuntime.AssertXcodeVersion(11, 4);

            imageUrl  = NSBundle.MainBundle.GetUrlForResource("square", "gif");
            imageData = NSData.FromUrl(imageUrl);
        }
Ejemplo n.º 25
0
        public void AvailableDepthDataTypesTest()
        {
#if !MONOMAC
            TestRuntime.AssertDevice();
#endif
            TestRuntime.AssertXcodeVersion(9, 0);

            // xamarinmonkey.heic is the new photo format, also this one includes depth data
            var imgdata = NSData.FromUrl(NSBundle.MainBundle.GetUrlForResource("xamarinmonkey", "heic", "CoreImage"));
            Assert.NotNull(imgdata, "imgdata");

            var imageSource = CGImageSource.FromData(imgdata);
            Assert.NotNull(imageSource, "imageSource");

            // fetching the image count works around a crash in CopyAuxiliaryDataInfo on macOS 10.15 (https://github.com/xamarin/maccore/issues/1802).
            Assert.AreNotEqual(0, imageSource.ImageCount, "ImageCount");

            var info = imageSource.CopyAuxiliaryDataInfo(0, CGImageAuxiliaryDataType.Disparity);
            Assert.NotNull(info, "info");

            NSError err;
            var     depthData = AVDepthData.Create(info, out err);
            Assert.NotNull(depthData, "depthData");
            Assert.NotNull(depthData.AvailableDepthDataTypes, "AvailableDepthDataTypes");
        }
Ejemplo n.º 26
0
        void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            UIImage image = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data   = image.AsJPEG(1);
                Stream stream = data.AsStream();
                UnregisterEventHandlers();
                // Set the Stream as the completion of the Task
                taskCompletionSource.SetResult(
                    new Tuple <Stream, string, Services.MGFileType>
                        (stream, args.ImageUrl.AbsoluteString, Services.MGFileType.Photo));
            }
            else if (args.MediaUrl != null)
            {
                NSData data   = NSData.FromUrl(args.MediaUrl);
                Stream stream = data.AsStream();
                UnregisterEventHandlers();
                taskCompletionSource.SetResult(
                    new Tuple <Stream, string, Services.MGFileType>
                        (stream, args.MediaUrl.AbsoluteString, Services.MGFileType.Video));
            }
            else
            {
                UnregisterEventHandlers();
                taskCompletionSource.SetResult(null);
            }
            imagePicker.DismissViewController(true, null);
        }
Ejemplo n.º 27
0
        async void LinkedInAuth_Completed(object sender, AuthenticatorCompletedEventArgs e)
        {
            if (e.IsAuthenticated)
            {
                var request = new OAuth2Request(
                    "GET",
                    new Uri("https://api.linkedin.com/v1/people/~:(id,firstName,lastName,headline,picture-url,summary,educations,three-current-positions,honors-awards,site-standard-profile-request,location,api-standard-profile-request,phone-numbers)?"
                            + "format=json"
                            + "&oauth2_access_token="
                            + e.Account.Properties["access_token"]),
                    null,
                    e.Account);

                var linkedInResponse = await request.GetResponseAsync();

                var json         = linkedInResponse.GetResponseText();
                var linkedInUser = JsonValue.Parse(json);

                var name        = linkedInUser["firstName"] + " " + linkedInUser["lastName"];
                var id          = linkedInUser["id"];
                var description = linkedInUser["headline"];
                var picture     = linkedInUser["pictureUrl"];

                LblName.Text += name;
                //IdLabel.Text += id;
                LblDescription.Text = description;
                ImgVUser.Image      = UIImage.LoadFromData(NSData.FromUrl(new NSUrl(picture)));
            }
            DismissViewController(true, null);
        }
Ejemplo n.º 28
0
        public void Https()
        {
#if __WATCHOS__
            if (global::ObjCRuntime.Runtime.Arch == global::ObjCRuntime.Arch.DEVICE)
            {
                // This error is returned: Error: The file “robots.txt” couldn’t be opened. The file “robots.txt” couldn’t be opened.
                Assert.Ignore("NSData.FromUrl doesn't seem to work in watchOS");
            }
#endif
            // Https seems broken on our macOS 10.9 bot, so skip this test.
            TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 10, throwIfOtherPlatform: false);

            // we have network issues, try several urls, if one works, be happy, else fail
            for (var i = 0; i < NetworkResources.RobotsUrls.Length; i++)
            {
                NSError error;
                using (var nsUrl = new NSUrl(NetworkResources.RobotsUrls [i]))
                    using (var x = NSData.FromUrl(nsUrl, NSDataReadingOptions.Uncached, out error)) {
                        if (error != null)
                        {
                            continue;
                        }
                        Assert.That(x != null);
                        Assert.That(x.Length > 0);
                        return;
                    }
            }
            Assert.Fail("None of the urls could be fetch.");
        }
Ejemplo n.º 29
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NavigationItem.RightBarButtonItem          = new UIBarButtonItem(UIBarButtonSystemItem.Add);
            NavigationItem.RightBarButtonItem.Clicked += delegate { UploadPicture(); };

            _uploader = new PhotoUploader();
            _listener = new PhotoListener();

            _listener.NewPhotosReceived += (sender, urls) =>
            {
                InvokeOnMainThread(() =>
                {
                    foreach (var url in urls)
                    {
                        _imageSection.Add(
                            new ImageStringElement(DateTime.Now.ToString(),
                                                   UIImage.LoadFromData(NSData.FromUrl(new NSUrl(url))))
                            );
                    }
                });
            };

            _listener.StartListening();
        }
Ejemplo n.º 30
0
        public override bool CopyFromRemote(string url, string toPath)
        {
            try {
                // delete file if already exists
                string path = Path.Combine(this.GetDirectoryRoot().FullName, toPath);
                //TODO Review
                if (!CheckSecurePath(path))
                {
                    return(false);
                }
                NSUrl  nsurl = new NSUrl(url);
                NSData data  = NSData.FromUrl(nsurl);
                if (data != null)
                {
                    // remove previous existing file
                    if (File.Exists(path))
                    {
                        this.DeleteFile(new FileData(path));
                    }
                    // create an empty file
                    FileData toFile = this.CreateFile(toPath);

                    byte[] buffer = new byte[data.Length];
                    Marshal.Copy(data.Bytes, buffer, 0, buffer.Length);
                    // write contents and return result
                    return(this.WriteFile(toFile, buffer, false));
                }
                // don't create/replace any file if NSData couldn't be obtained from remote path
            } catch (Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error copying from [" + url + "] to file [" + toPath + "]", ex);
            }
            return(false);
        }