Inheritance: IShareOperation
		public async void Initialize(ShareOperation operation)
		{
			if (operation != null)
			{
				this.currentOperation = operation;

				if (operation.Data.Contains(StandardDataFormats.StorageItems))
				{
					try
					{
						this.ClearItems();
					}
					catch
					{
					}

					var sharedStorageItems = await operation.Data.GetStorageItemsAsync();

					foreach (var item in sharedStorageItems.OfType<StorageFile>())
					{
						this.SharedItems.Add(new SharedFileViewModel(item));
					}

					this.UploadCommand.RaiseCanExecuteChanged();
					this.ShareCommand.RaiseCanExecuteChanged();
				} 
			}
		}
 public async void Initialize(ShareOperation share)
 {
     _share = share;
     _share.ReportStarted();
     await _share.Data.CopyTo(_values);
     _share.ReportDataRetrieved();
 }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter is ShareOperation)
            {
                this.shareOperation = e.Parameter as ShareOperation;

                if (this.shareOperation == null)
                {
                    return;
                }

                this.viewModel.Uri = await this.shareOperation.Data.GetWebLinkAsync();
                this.viewModel.Comment = this.shareOperation.Data.Properties.Title;
            }
            else if (e.Parameter is GifViewModel)
            {
                var model = e.Parameter as GifViewModel;
                this.streamKey = model.StreamKey;
                this.viewModel.Uri = new Uri(model.Gif, UriKind.RelativeOrAbsolute);

                if (this.streamKey != null)
                {
                    this.StreamSelector.Visibility = Visibility.Collapsed;
                    this.ShareButton.Visibility = Visibility.Visible;
                }
            }

            base.OnNavigatedTo(e);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            BottomControls.Visibility = Visibility.Collapsed; // To avoid control flashes as we transit this page quickly
            base.OnNavigatedTo(e); // Glenn adds. This will set the _pagekey variable, which otherwise would be null and later throw an exception in OnNavigatedFrom.
            var args = e.Parameter as ShareTargetActivatedEventArgs;
            
            if (args == null)
            {
                await CaptureButton_ClickImpl();// was before Release 7, but need await to not show bottom controls flashing: CaptureButton_Click(this, null); // Glenn adds
                BottomControls.Visibility = Visibility.Visible;
                return;
            }
            BottomControls.Visibility = Visibility.Visible;
            Caption.Text = App.CurrentPatient.ImageCaption; // TO DO: Make this actually useful for "Original filename: <whatever>" when image picked from file.
            // TO DO... distinguish NewReport & ViewEdit handling of this

            _shareOperation = args.ShareOperation;

            if (_shareOperation.Data.Contains(
                StandardDataFormats.Bitmap))
            {
                _bitmap = await _shareOperation.Data.GetBitmapAsync();
                await ProcessBitmap();
            }
            else if (_shareOperation.Data.Contains(
                StandardDataFormats.StorageItems))
            {
                _items = await _shareOperation.Data.GetStorageItemsAsync();
                await ProcessStorageItems();
            }
            else _shareOperation.ReportError(
                "TriagePic was unable to find a valid bitmap.");
        }
        public async Task ShareAsync(ShareOperation shareOperation)
        {
            _shareOperation = shareOperation;
            shareOperation.ReportStarted();
            var dataPackageView = shareOperation.Data;

            RequestTitle = shareOperation.Data.Properties.Title;
            RequestDescription = shareOperation.Data.Properties.Description;

            try
            {
                if ( dataPackageView.IsTextMessage() )
                {
                    IsTextRequest = true;
                    TextShareValue = await dataPackageView.GetTextAsync();
                }
                else if (dataPackageView.IsUrlMessage())
                {
                    IsUrlRequest = true;
                    var foundUri = await dataPackageView.GetUriAsync();

                    UrlShareValue = foundUri.AbsoluteUri;
                }
                else if (dataPackageView.IsStorageItemsMessage())
                {
                    IsStorageRequest = true;
                    var storageItems = await dataPackageView.GetStorageItemsAsync();
                    if ( storageItems.Any())
                    {
                        var storageItem = storageItems.First();
                        if ( storageItem.IsOfType(StorageItemTypes.File))
                        {
                            StorageFileName = storageItem.Name;
                            var thumbNail = dataPackageView.Properties.Thumbnail;
                            var thumbnailStream = await thumbNail.OpenReadAsync();

                            ImageShareValue = new BitmapImage();
                            ImageShareValue.SetSource(thumbnailStream);
                        }
                    }
                }
                else if (dataPackageView.IsImageMessage())
                {
                    IsImageRequest = true;
                    var imageRecieved = await dataPackageView.GetBitmapAsync();
                    var imageStream = await imageRecieved.OpenReadAsync();

                    ImageShareValue = new BitmapImage();
                    ImageShareValue.SetSource(imageStream);
                }
            }
            catch (Exception e)
            {
                shareOperation.ReportError(e.Message);               
                RequestDescription = e.Message;
            }
            

            shareOperation.ReportDataRetrieved();
        }
		public async Task<ReceivedShareItem> GetReceivedSharedItemAsync(ShareOperation sourceOperation)
		{
			var packageView = sourceOperation.Data;
			ReceivedShareItem rval = await FetchDataFromPackageViewAsync(packageView);
			rval.QuickLinkId = sourceOperation.QuickLinkId;
			return rval;
		}
        /// <summary>
        /// 他のアプリケーションがこのアプリケーションを介してコンテンツの共有を求めた場合に呼び出されます。
        /// </summary>
        /// <param name="args">Windows と連携して処理するために使用されるアクティベーション データ。</param>
        public async void Activate(ShareTargetActivatedEventArgs args)
        {
            this.currentModel = BookmarkerModel.GetDefault();
            await this.currentModel.LoadAsync();

            this._shareOperation = args.ShareOperation;

            // ビュー モデルを使用して、共有されるコンテンツのメタデータを通信します
            var shareProperties = this._shareOperation.Data.Properties;
            var thumbnailImage = new BitmapImage();
            this.DefaultViewModel["Title"] = shareProperties.Title;
            this.DefaultViewModel["Description"] = shareProperties.Description;
            this.DefaultViewModel["Image"] = thumbnailImage;
            this.DefaultViewModel["Sharing"] = false;
            this.DefaultViewModel["ShowImage"] = false;
            this.DefaultViewModel["Comment"] = String.Empty;
            this.DefaultViewModel["SupportsComment"] = true;

            this.addBookmarkView.Title = shareProperties.Title;
            this.addBookmarkView.Uri = (await this._shareOperation.Data.GetUriAsync()).ToString();

            Window.Current.Content = this;
            Window.Current.Activate();

            // 共有されるコンテンツの縮小版イメージをバックグラウンドで更新します
            if (shareProperties.Thumbnail != null)
            {
                var stream = await shareProperties.Thumbnail.OpenReadAsync();
                thumbnailImage.SetSource(stream);
                this.DefaultViewModel["ShowImage"] = true;
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {

            this.so = (ShareOperation)e.Parameter;
            sharedContentTitle.Text = so.Data.Properties.Title.ToString();


            if (this.so.Data.Contains(StandardDataFormats.Text))
            {
                sharedText.Text = await this.so.Data.GetTextAsync();

            }

            //if (this.so.Data.Contains(StandardDataFormats.Html))
            //{
            //    string HtmlString = await this.so.Data.GetHtmlFormatAsync();
            //    string htmlFragment = HtmlFormatHelper.GetStaticFragment(HtmlString);


            //    ShareWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>"); ;
            //}

            //if (this.so.Data.Contains(StandardDataFormats.StorageItems))
            //{
            //    sharedStorageItems = await this.so.Data.GetStorageItemsAsync();

            //    sharedFiles.Text = "Share File Name: " + sharedStorageItems[0].Path;

            //}                           


        }
        /// <summary>
        /// Invoked when another application wants to share content through this application.
        /// </summary>
        /// <param name="args">Activation data used to coordinate the process with Windows.</param>
        public void Activate(ShareTargetActivatedEventArgs args)
        {
            // set...
            this.ShareOperation = args.ShareOperation;

            // show...
            Window.Current.Content = this;
            Window.Current.Activate();
        }
Beispiel #10
0
        /// <summary>
        /// Wird aufgerufen, wenn eine andere Anwendung Inhalte durch diese Anwendung freigeben möchte.
        /// </summary>
        /// <param name="e">Aktivierungsdaten zum Koordinieren des Prozesses mit Windows.</param>
        public async void Activate(ShareTargetActivatedEventArgs e)
        {
            this.shareOperation = e.ShareOperation;

            var shareProperties = this.shareOperation.Data.Properties;
            this.DefaultViewModel["Title"] = shareProperties.Title; // Gets the title from the sender app.
            this.DefaultViewModel["Description"] = shareProperties.Description; // Gets the description from the sender app.
            this.DefaultViewModel["Sharing"] = false;
            this.DefaultViewModel["Url"] = await shareOperation.Data.GetWebLinkAsync(); // Because wallabag is saving links, the web link is the most important thing in this code block.
            Window.Current.Content = this;
            Window.Current.Activate();
        }
Beispiel #11
0
        public void Activate(ShareTargetActivatedEventArgs args)
        {
            DefaultViewModel["Sharing"] = false;

            _ShareOperation = args.ShareOperation;
            DataPackagePropertySetView shareProperties = _ShareOperation.Data.Properties;
            DefaultViewModel["Link"] = new Link
                                           {
                                               Name = shareProperties.Title,
                                               Uri = new Uri(shareProperties.Description)
                                           };

            Window.Current.Content = this;
            Window.Current.Activate();
        }
 private void OnClipboardContentChanged(object sender, object e)
 {
     if (_share != null)
     {
         try
         {
             _share.ReportCompleted();
             _share = null;
         }
         catch(Exception ex)
         {
             Debug.WriteLine(ex);
             _share.ReportError(ex.ToString());
         }
     }
 }
Beispiel #13
0
        /// <summary>
        /// 他のアプリケーションがこのアプリケーションを介してコンテンツの共有を求めた場合に呼び出されます。
        /// </summary>
        /// <param name="args">Windows と連携して処理するために使用されるアクティベーション データ。</param>
        public void Activate(ShareTargetActivatedEventArgs args)
        {
            this._shareOperation = args.ShareOperation;

            // ビュー モデルを使用して、共有されるコンテンツのメタデータを通信します
            var shareProperties = this._shareOperation.Data.Properties;

            this.DefaultViewModel["Title"]       = shareProperties.Title;
            this.DefaultViewModel["Description"] = shareProperties.Description;
            this.DefaultViewModel["Sharing"]     = false;
            Window.Current.Content = this;
            Window.Current.Activate();

            // 共有データを選択するためのリストとサムネイルを準備する
            this.DefaultViewModel["SharedItems"] = this.sharedItems;
            AddSharedItemsAsync(this._shareOperation);
        }
Beispiel #14
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (await DeviceName == null)
     {
         myName = "Unnamed Device";
     }
     else
     {
         myName = await DataStorage.GetStoredItemAsync("myName");
     }
     if (await DeviceName == null)
     {
         deviceName.Text = "";
     }
     else deviceName.Text = myName;
     deviceName.TextChanged += setNewName;
     try
     {
         if ((await ((ShareOperation)e.Parameter).Data.GetStorageItemsAsync()).Count > 0)
         {
             fileToShare = (StorageFile)(await ((ShareOperation)e.Parameter).Data.GetStorageItemsAsync())[0];
             shareOperation = (ShareOperation)e.Parameter;
         }
         else fileToShare = null;
     }
     catch (InvalidCastException)
     {
         fileToShare = null;
     }
     progressStop();
     Communicator.FileReceived += this.saveFile;
     Communicator.ProgressRepport += this.progressRepport;
     Communicator.ProgressIndeterminate += this.progressIndeterminate;
     Communicator.ProgressStop += this.progressStop;
     if (NetworkInformation.GetInternetConnectionProfile() == null)
     {
         await DialogBoxes.ShowMessageBox("No network access, please enable network and restart");
     }
     else
     {
         await Communicator.Init(myName);
         await Communicator.DiscoverDevices();
         peerList.DataContext = Communicator.Peers;
     }
 }
        public async Task SetupShareDataAsync(ShareOperation share)
        {
            // store the share operation - we need to do this to hold a 
            // reference otherwise the sharing subsystem will assume 
            // that we've finished...
            this.ShareOperation = share;

            // get the properties out...
            var data = share.Data;
            var props = data.Properties;
            this.Title = props.Title;
            this.Description = props.Description;

            // now the text...
            if (data.Contains(StandardDataFormats.Text))
                this.SharedText = await data.GetTextAsync();

            // do we have an image? if so, load it...
            if (data.Contains(StandardDataFormats.StorageItems) || data.Contains(StandardDataFormats.Bitmap))
            {
                IRandomAccessStreamReference reference = null;

                // load the first one...
                if (data.Contains(StandardDataFormats.StorageItems))
                {
                    var file = (IStorageFile)(await data.GetStorageItemsAsync()).FirstOrDefault();
                    reference = RandomAccessStreamReference.CreateFromFile(file);
                }
                else
                    reference = await data.GetBitmapAsync();

                // load it into an image...
                var image = new BitmapImage();
                using (var stream = await reference.OpenReadAsync())
                    image.SetSource(stream);

                // set...
                this.SharedImage = image;
                this.ShowImage = true;
            }

            // tell the OS that we have the data...
            share.ReportDataRetrieved();
        }
        public async void Activate(ShareTargetActivatedEventArgs args)
        {
            _shareOperation = args.ShareOperation;
            DataPackageView dpv = args.ShareOperation.Data;

            var props = dpv.Properties;
            txtTitle.Text = props.Title;
            txtDescription.Text = props.Description;

            var thumbnailImage = new BitmapImage();
            if (props.Thumbnail != null)
            {
                var s = await props.Thumbnail.OpenReadAsync();
                thumbnailImage.SetSource(s);
            }
            img.Source = thumbnailImage;

            Window.Current.Content = this;
            Window.Current.Activate();
        }
Beispiel #17
0
        /// <summary>
        /// 他のアプリケーションがこのアプリケーションを介してコンテンツの共有を求めた場合に呼び出されます。
        /// </summary>
        /// <param name="e">Windows と連携して処理するために使用されるアクティベーション データ。</param>
        public async void Activate(ShareTargetActivatedEventArgs e)
        {
            this._shareOperation = e.ShareOperation;

            // ビュー モデルを使用して、共有されるコンテンツのメタデータを通信します
            var shareProperties = this._shareOperation.Data.Properties;

            this.DefaultViewModel["Title"]                 = shareProperties.Title;
            this.DefaultViewModel["Description"]           = shareProperties.Description;
            this.DefaultViewModel["Sharing"]               = false;
            this.defaultViewModel["LoadingItem"]           = true;
            this.defaultViewModel["EditButtonsVisibility"] = Visibility.Collapsed;
            Window.Current.Content = this;
            Window.Current.Activate();

            await AddSharedItemsAsync(this._shareOperation);

            this.defaultViewModel["EditButtonsVisibility"] = Visibility.Visible;
            this.defaultViewModel["LoadingItem"]           = false;
        }
Beispiel #18
0
        public ShareViewModel(ShareOperation arguments)
        {
            client = AppBootstrapper.Client;

            _shareOperation = arguments;
            Title = _shareOperation.Data.Properties.Title;

            if (_shareOperation.Data.Contains(StandardDataFormats.Bitmap))
            {
                Image = new BitmapImage();
                InitiliseBitmap();
            }

            if (_shareOperation.Data.Contains(StandardDataFormats.StorageItems))
            {
                Files = new ObservableCollection<IStorageFile>();
                InitiliseStorageItems();
            }

            Initilise();
        }
		/// <summary>
		///     Invoked when another application wants to share content through this application.
		/// </summary>
		/// <param name="e">Activation data used to coordinate the process with Windows.</param>
		public async void Activate(ShareTargetActivatedEventArgs e)
		{
			_shareOperation = e.ShareOperation;

			// Communicate metadata about the shared content through the view model
			var shareProperties = _shareOperation.Data.Properties;
			var thumbnailImage = new BitmapImage();
			DefaultViewModel["Title"] = shareProperties.Title;
			DefaultViewModel["Description"] = shareProperties.Description;
			DefaultViewModel["Image"] = thumbnailImage;
			DefaultViewModel["Sharing"] = false;
			DefaultViewModel["ShowImage"] = false;
			DefaultViewModel["Comment"] = String.Empty;
			DefaultViewModel["Placeholder"] = "Add a comment";
			DefaultViewModel["SupportsComment"] = true;
			Window.Current.Content = this;
			Window.Current.Activate();

			// Update the shared content's thumbnail image in the background
			if (shareProperties.Thumbnail != null)
			{
				var stream = await shareProperties.Thumbnail.OpenReadAsync();
				thumbnailImage.SetSource(stream);
				DefaultViewModel["ShowImage"] = true;
			}



			var files = await _shareOperation.Data.GetStorageItemsAsync();

			if (!files.Any()) return;

			foreach (var file in files.Where(f => f.IsOfType(StorageItemTypes.File)).Cast<StorageFile>())
			{
				await file.CopyAsync(ApplicationData.Current.LocalFolder);
			}
		}
        public void Activate(ShareOperation shareOperation)
        {
            string title = null;
            string description = null;
            try
            {
                _shareOperation = shareOperation;

                title = _shareOperation.Data.Properties.Title;
                description = _shareOperation.Data.Properties.Description;
                foreach (var format in _shareOperation.Data.AvailableFormats)
                {
                    _shareFormats.Add(format);
                }

                Title = title;
                Description = description;

            }
            catch (Exception ex)
            {
                _shareOperation.ReportError(ex.Message);
            }
        }
 public ShareTargetViewModel(ShareOperation operation)
 {
     this.operation = operation;
 }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _shareOperation = (ShareOperation) e.Parameter;

            ((ShareViewModel) DataContext).ShareAsync(_shareOperation);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            _shareOperation = (ShareOperation) e.Parameter;

            await Task.Factory.StartNew(async () =>
            {
                _title = _shareOperation.Data.Properties.Title;
                _description = _shareOperation.Data.Properties.Description;

                if (_shareOperation.Data.Contains(StandardDataFormats.Bitmap))
                {
                    _sharedBitmapStreamRef = await _shareOperation.Data.GetBitmapAsync();
                }
                else if (_shareOperation.Data.Contains(StandardDataFormats.StorageItems))
                {
                    _sharedStorageItems = await _shareOperation.Data.GetStorageItemsAsync();
                }

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    bool operationSuccess = false;
                    string link = String.Empty;

                    UploadProgressRing.IsActive = true;
                    UploadStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;


                    if (_sharedBitmapStreamRef != null)
                    {
                        IRandomAccessStreamWithContentType stream = await _sharedBitmapStreamRef.OpenReadAsync();
                        Stream imageStream = stream.AsStreamForRead();

                        UploadStatus.Text = "Uploading image...";

                        Basic<UploadData> uploadResult = await _api.Upload(imageStream, null, null, null, null);

                        if (uploadResult != null && uploadResult.Success)
                        {
                            operationSuccess = true;
                            link = uploadResult.Data.Link;
                        }
                        else
                        {
                            UploadStatus.Text = "Failed to upload image.";
                        }

                    }
                    else if (_sharedStorageItems != null)
                    {
                        if (_sharedStorageItems.Count > 1)
                        {

                            List<string> uploadedImageIDs = new List<string>();

                            int currentImageCount = 0;
                            foreach (IStorageItem item in _sharedStorageItems)
                            {
                                currentImageCount++;
                                UploadStatus.Text = String.Format("Uploading image {0} of {1}...", currentImageCount, _sharedStorageItems.Count);

                                if (item.IsOfType(StorageItemTypes.File))
                                {
                                    StorageFile file = (StorageFile)item;
                                    Basic<UploadData> uploadResult = await _api.Upload(file, null, null, null);

                                    if (uploadResult != null && uploadResult.Success)
                                    {
                                        uploadedImageIDs.Add(uploadResult.Data.ID);
                                    }
                                    else
                                    {
                                        //TODO: Log this error.
                                    }
                                }
                            }

                            UploadStatus.Text = "Creating album...";
                            Basic<AlbumCreateData> albumCreationResult = await _api.CreateAlbum(uploadedImageIDs.ToArray(), null, null, null);
                            if (albumCreationResult != null && albumCreationResult.Success)
                            {
                                operationSuccess = true;
                                link = String.Format("http://imgur.com/a/{0}", albumCreationResult.Data.ID);
                            }
                            else
                            {
                                UploadStatus.Text = "Failed to create album.";
                            }
                        }
                        else if (_sharedStorageItems.Count == 1)
                        {
                            IStorageItem item = _sharedStorageItems[0];

                            if (item.IsOfType(StorageItemTypes.File))
                            {
                                UploadStatus.Text = "Uploading image...";

                                StorageFile file = (StorageFile)item;
                                Basic<UploadData> uploadResult = await _api.Upload(file, null, null, null);

                                if (uploadResult != null && uploadResult.Success)
                                {
                                    operationSuccess = true;
                                    link = uploadResult.Data.Link;
                                }
                                else
                                {
                                    UploadStatus.Text = "Failed to upload image.";
                                }
                            }
                        }

                        
                    }

                    UploadProgressRing.IsActive = false;

                    if (operationSuccess)
                    {
                        UploadStatus.Text = "Upload Complete";
                        UploadProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                        ImgurURL.Value = link;
                        ImgurURL.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    else
                    {
                        UploadStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }

                });
            });

        }
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    share = e.Parameter as ShareOperation;

    await Task.Factory.StartNew(async () =>
    {
        title = share.Data.Properties.Title;
        description = share.Data.Properties.Description;
        thumbImage = share.Data.Properties.Thumbnail;

        //IF THERE WAS FORMATTED TEXT SHARED
        if (share.Data.Contains(StandardDataFormats.Html))
        {
            formattedText = await share.Data.GetHtmlFormatAsync();
        }
        //IF THERE WAS A URI SHARED
        if (share.Data.Contains(StandardDataFormats.Uri))
        {
            uri = await share.Data.GetUriAsync();
        }
        //IF THERE WAS UNFORMATTED TEXT SHARED
        if (share.Data.Contains(StandardDataFormats.Text))
        {
            text = await share.Data.GetTextAsync();
        }
        //IF THERE WERE FILES SHARED
        if (share.Data.Contains(StandardDataFormats.StorageItems))
        {
            storageItems = await share.Data.GetStorageItemsAsync();
        }
        //IF THERE WAS CUSTOM DATA SHARED
        if (share.Data.Contains(customDataFormat))
        {
            customData = await share.Data.GetTextAsync(customDataFormat);
        }
        //IF THERE WERE IMAGES SHARED.
        if (share.Data.Contains(StandardDataFormats.Bitmap))
        {
            bitmapImage = await share.Data.GetBitmapAsync();
        }

        //MOVING BACK TO THE UI THREAD, THIS IS WHERE WE POPULATE OUR INTERFACE.
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                TitleBox.Text = title;
                DescriptionBox.Text = description;

                if (text != null)
                    UnformattedTextBox.Text = text;
                if (uri != null)
                {
                    UriButton.Content = uri.ToString();
                    UriButton.NavigateUri = uri;
                }

                if (formattedText != null)
                    HTMLTextBox.NavigateToString(HtmlFormatHelper.GetStaticFragment(formattedText));

                if (bitmapImage != null)
                {
                    IRandomAccessStreamWithContentType bitmapStream = await this.bitmapImage.OpenReadAsync();
                    BitmapImage bi = new BitmapImage();
                    bi.SetSource(bitmapStream);
                    WholeImage.Source = bi;

                    bitmapStream = await this.thumbImage.OpenReadAsync();
                    bi = new BitmapImage();
                    bi.SetSource(bitmapStream);
                    ThumbImage.Source = bi;
                }

                if (customData != null)
                {
                    StringBuilder receivedStrings = new StringBuilder();
                    JsonObject customObject = JsonObject.Parse(customData);
                    if (customObject.ContainsKey("type"))
                    {
                        if (customObject["type"].GetString() == "http://schema.org/Person")
                        {
                            receivedStrings.AppendLine("Type: " + customObject["type"].Stringify());
                            JsonObject properties = customObject["properties"].GetObject();
                            receivedStrings.AppendLine("Image: " + properties["image"].Stringify());
                            receivedStrings.AppendLine("Name: " + properties["name"].Stringify());
                            receivedStrings.AppendLine("Affiliation: " + properties["affiliation"].Stringify());
                            receivedStrings.AppendLine("Birth Date: " + properties["birthDate"].Stringify());
                            receivedStrings.AppendLine("Job Title: " + properties["jobTitle"].Stringify());
                            receivedStrings.AppendLine("Nationality: " + properties["Nationality"].Stringify());
                            receivedStrings.AppendLine("Gender: " + properties["gender"].Stringify());
                        }
                        CustomDataBox.Text = receivedStrings.ToString();
                    }
                }
            });
        });

}
 private void CheckAndClearShareOperation()
 {
     if (_shareOperation != null)
     {
         _shareOperation.ReportCompleted();
         _shareOperation = null;
     }
 }
        public async Task ActivateAsync(ShareTargetActivatedEventArgs args)
        {
            try
            {
                shareOperation = args.ShareOperation;

                LoadTargets();
                await ExtractShareData(args);
            }
            catch
            {
                shareOperation.ReportError("Could not determine the type of data to share");
            }
        }
Beispiel #27
0
            // *** Constructors ***

            public ShareOperationProxy(ShareOperation shareOperation)
            {
                this.shareOperation = shareOperation;
            }
Beispiel #28
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            _shareOperation = e.Parameter as ShareOperation;

            if (_shareOperation != null)
            {
                ViewModel.Url = (await _shareOperation.Data.GetWebLinkAsync()).ToString();
                await ViewModel.LoadCurrentPageAsync();

                if (ViewModel.CurrentPage.IsParsed)
                    MainWebView.NavigateToString(ViewModel.CurrentPage.ParsedPage.Content);
                else
                    MainWebView.Navigate(ViewModel.CurrentPage.NotParsedPage);
            }
        }
Beispiel #29
0
        private static async Task<PrintRequest> MakeRequestAsync( ShareOperation operation )
        {
            var formats = operation.Data.AvailableFormats;
            if ( formats.Contains( StandardDataFormats.StorageItems ) )
            {
                var items = await operation.Data.GetStorageItemsAsync();

                // TODO support multiple files.
                // (atomic printing would be nice for groups of files)

                var file = items.OfType<StorageFile>().FirstOrDefault();
                if ( file != null )
                {
                    // Passing the file as an URI is required,
                    // but it can't be converted back to a StorageFile if it's not in our app's folders.
                    var copy = await file.CopyAsync( ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.GenerateUniqueName );
                    return new PrintRequest( file.Name, new Uri( copy.Path, UriKind.Absolute ) );
                }
            }

            // We can't display share errors on WP, so...
            return null;
        }
            // *** Constructors ***

            public ShareOperationProxy(ShareOperation shareOperation)
            {
                _shareOperation = shareOperation;
                this.Data = new SharePackageView(shareOperation.Data);
            }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // It is recommended to only retrieve the ShareOperation object in the activation handler, return as
            // quickly as possible, and retrieve all data from the share target asynchronously.

            this.shareOperation = (ShareOperation)e.Parameter;

            await Task.Factory.StartNew(async () =>
            {
                // Retrieve the data package properties.
                this.sharedDataTitle = this.shareOperation.Data.Properties.Title;
                this.sharedDataDescription = this.shareOperation.Data.Properties.Description;
                this.sharedDataPackageFamilyName = this.shareOperation.Data.Properties.PackageFamilyName;
                this.sharedDataContentSourceWebLink = this.shareOperation.Data.Properties.ContentSourceWebLink;
                this.sharedDataContentSourceApplicationLink = this.shareOperation.Data.Properties.ContentSourceApplicationLink;
                this.sharedDataLogoBackgroundColor = this.shareOperation.Data.Properties.LogoBackgroundColor;
                this.sharedDataSquare30x30Logo = this.shareOperation.Data.Properties.Square30x30Logo;
                this.sharedThumbnailStreamRef = this.shareOperation.Data.Properties.Thumbnail;
                this.shareQuickLinkId = this.shareOperation.QuickLinkId;

                // Retrieve the data package content.
                // The GetWebLinkAsync(), GetTextAsync(), GetStorageItemsAsync(), etc. APIs will throw if there was an error retrieving the data from the source app.
                // In this sample, we just display the error. It is recommended that a share target app handles these in a way appropriate for that particular app.
                if (this.shareOperation.Data.Contains(StandardDataFormats.WebLink))
                {
                    try
                    {
                        this.sharedWebLink = await this.shareOperation.Data.GetWebLinkAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(StandardDataFormats.ApplicationLink))
                {
                    try
                    {
                        this.sharedApplicationLink = await this.shareOperation.Data.GetApplicationLinkAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(StandardDataFormats.Text))
                {
                    try
                    {
                        this.sharedText = await this.shareOperation.Data.GetTextAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(StandardDataFormats.StorageItems))
                {
                    try
                    {
                        this.sharedStorageItems = await this.shareOperation.Data.GetStorageItemsAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(dataFormatName))
                {
                    try
                    {
                        this.sharedCustomData = await this.shareOperation.Data.GetTextAsync(dataFormatName);
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(StandardDataFormats.Html))
                {
                    try
                    {
                        this.sharedHtmlFormat = await this.shareOperation.Data.GetHtmlFormatAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }

                    try
                    {
                        this.sharedResourceMap = await this.shareOperation.Data.GetResourceMapAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (this.shareOperation.Data.Contains(StandardDataFormats.Bitmap))
                {
                    try
                    {
                        this.sharedBitmapStreamRef = await this.shareOperation.Data.GetBitmapAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }

                // In this sample, we just display the shared data content.

                // Get back to the UI thread using the dispatcher.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    DataPackageTitle.Text = this.sharedDataTitle;
                    DataPackageDescription.Text = this.sharedDataDescription;
                    DataPackagePackageFamilyName.Text = this.sharedDataPackageFamilyName;
                    if (this.sharedDataContentSourceWebLink != null)
                    {
                        DataPackageContentSourceWebLink.Text = this.sharedDataContentSourceWebLink.AbsoluteUri;
                    }
                    if (this.sharedDataContentSourceApplicationLink != null)
                    {
                        DataPackageContentSourceApplicationLink.Text = this.sharedDataContentSourceApplicationLink.AbsoluteUri;
                    }

                    if (this.sharedDataSquare30x30Logo != null)
                    {
                        IRandomAccessStreamWithContentType logoStream = await this.sharedDataSquare30x30Logo.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(logoStream);
                        LogoHolder.Source = bitmapImage;
                        LogoBackground.Background = new SolidColorBrush(this.sharedDataLogoBackgroundColor);
                        LogoArea.Visibility = Visibility.Visible;
                    }

                    if (!String.IsNullOrEmpty(this.shareOperation.QuickLinkId))
                    {
                        SelectedQuickLinkId.Text = this.shareQuickLinkId;
                    }

                    if (this.sharedThumbnailStreamRef != null)
                    {
                        IRandomAccessStreamWithContentType thumbnailStream = await this.sharedThumbnailStreamRef.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnailStream);
                        ThumbnailHolder.Source = bitmapImage;
                        ThumbnailArea.Visibility = Visibility.Visible;
                    }

                    if (this.sharedWebLink != null)
                    {
                        AddContentValue("WebLink: ", this.sharedWebLink.AbsoluteUri);
                    }
                    if (this.sharedApplicationLink != null)
                    {
                        AddContentValue("ApplicationLink: ", this.sharedApplicationLink.AbsoluteUri);
                    }
                    if (this.sharedText != null)
                    {
                        AddContentValue("Text: ", this.sharedText);
                    }
                    if (this.sharedStorageItems != null)
                    {
                        // Display the name of the files being shared.
                        StringBuilder fileNames = new StringBuilder();
                        for (int index = 0; index < this.sharedStorageItems.Count; index++)
                        {
                            fileNames.Append(this.sharedStorageItems[index].Name);
                            if (index < this.sharedStorageItems.Count - 1)
                            {
                                fileNames.Append(", ");
                            }
                        }
                        fileNames.Append(".");

                        AddContentValue("StorageItems: ", fileNames.ToString());
                    }
                    if (this.sharedCustomData != null)
                    {
                        // This is an area to be especially careful parsing data from the source app to avoid buffer overruns.
                        // This sample doesn't perform data validation but will catch any exceptions thrown.
                        try
                        {
                            StringBuilder receivedStrings = new StringBuilder();
                            JsonObject customObject = JsonObject.Parse(this.sharedCustomData);
                            if (customObject.ContainsKey("type"))
                            {
                                if (customObject["type"].GetString() == "http://schema.org/Book")
                                {
                                    // This sample expects the custom format to be of type http://schema.org/Book
                                    receivedStrings.AppendLine("Type: " + customObject["type"].Stringify());
                                    JsonObject properties = customObject["properties"].GetObject();
                                    receivedStrings.AppendLine("Image: " + properties["image"].Stringify());
                                    receivedStrings.AppendLine("Name: " + properties["name"].Stringify());
                                    receivedStrings.AppendLine("Book Format: " + properties["bookFormat"].Stringify());
                                    receivedStrings.AppendLine("Author: " + properties["author"].Stringify());
                                    receivedStrings.AppendLine("Number of Pages: " + properties["numberOfPages"].Stringify());
                                    receivedStrings.AppendLine("Publisher: " + properties["publisher"].Stringify());
                                    receivedStrings.AppendLine("Date Published: " + properties["datePublished"].Stringify());
                                    receivedStrings.AppendLine("In Language: " + properties["inLanguage"].Stringify());
                                    receivedStrings.Append("ISBN: " + properties["isbn"].Stringify());

                                    AddContentValue("Custom format data:" + Environment.NewLine, receivedStrings.ToString());
                                }
                                else
                                {
                                    NotifyUser("The custom format from the source app is not of type http://schema.org/Book", NotifyType.ErrorMessage);
                                }
                            }
                            else
                            {
                                NotifyUser("The custom format from the source app doesn't contain a type", NotifyType.ErrorMessage);
                            }
                        }
                        catch (Exception ex)
                        {
                            NotifyUser("Failed to parse the custom data - " + ex.Message, NotifyType.ErrorMessage);
                        }
                    }
                    if (this.sharedHtmlFormat != null)
                    {
                        string htmlFragment = HtmlFormatHelper.GetStaticFragment(this.sharedHtmlFormat);
                        if (!String.IsNullOrEmpty(htmlFragment))
                        {
                            AddContentValue("HTML: ");
                            ShareWebView.Visibility = Visibility.Visible;
                            ShareWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>");
                        }
                        else
                        {
                            NotifyUser("GetStaticFragment failed to parse the HTML from the source app", NotifyType.ErrorMessage);
                        }

                        // Check if there are any local images in the resource map.
                        if (this.sharedResourceMap.Count > 0)
                        {
                            ResourceMapValue.Text = "";
                            foreach (KeyValuePair<string, RandomAccessStreamReference> item in this.sharedResourceMap)
                            {
                                ResourceMapValue.Text += "\nKey: " + item.Key;
                            }
                            ResourceMapArea.Visibility = Visibility.Visible;
                        }
                    }
                    if (this.sharedBitmapStreamRef != null)
                    {
                        IRandomAccessStreamWithContentType bitmapStream = await this.sharedBitmapStreamRef.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(bitmapStream);
                        ImageHolder.Source = bitmapImage;
                        ImageArea.Visibility = Visibility.Visible;
                    }
                });
            });
        }
Beispiel #32
0
        protected override void WireMessages()
        {
            Messenger.Default.Register<NotificationMessage>(this, m =>
            {
                if (m.Notification.Equals(Constants.Messages.ReaderViewLeftMsg))
                {
                    ShowFinishedScreen = false;
                    if (_readerTimer != null && _readerTimer.IsEnabled)
                    {
                        _readerTimer.Stop();
                    }

                    var wordsRead = SelectedIndex * _settingsService.WordsAtATime;
                    var articleNotFinished = wordsRead < SelectedItem.WordCount;
                    if (articleNotFinished)
                    {
                        _roamingSettings.Set(SelectedItem.InternalId, wordsRead);
                    }
                    else
                    {
                        _roamingSettings.Remove(SelectedItem.InternalId);
                    }

                    SaveInProgressItems(wordsRead, !articleNotFinished);
                }
            });

            Messenger.Default.Register<ShareMessage>(this, async m =>
            {
                _shareOperation = (ShareOperation)m.Sender;
                if (_shareOperation.Data.Contains(StandardDataFormats.WebLink))
                {
                    var url = await _shareOperation.Data.GetWebLinkAsync();
                    var message = new UriSchemeMessage(url.ToString(), true, SchemeType.Read);

                    await SaveItemFromExternal(message, async () =>
                    {
                        var title = _loader.GetString("ShareErrorTitle");
                        await _messageBox.ShowAsync(_loader.GetString("ShareErrorText"), title, new List<string> { _loader.GetString("MessageBoxOk") });
                        _shareOperation.ReportError(title);
                    });
                }
                else
                {
                    _shareOperation.ReportCompleted();
                }
            });

            Messenger.Default.Register<UriSchemeMessage>(this, async m =>
            {
                if (m.SchemeType != SchemeType.Read)
                {
                    return;
                }

                await SaveItemFromExternal(m);
            });
        }