Exemplo n.º 1
0
        // 显示剪切板中的 html 数据
        private async void btnPasteHtml_Click(object sender, RoutedEventArgs e)
        {
            DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();

            if (dataPackageView.Contains(StandardDataFormats.Html))
            {
                try
                {
                    // 封装后的数据
                    string htmlFormat = await dataPackageView.GetHtmlFormatAsync();

                    // 封装前的数据
                    string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);

                    lblMsg.Text  = "htmlFormat(封装后的数据): ";
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += htmlFormat;
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += "htmlFragment(封装前的数据): ";
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += htmlFragment;
                }
                catch (Exception ex)
                {
                    lblMsg.Text = ex.ToString();
                }
            }
            else
            {
                lblMsg.Text = "剪切板中无 html 内容";
            }
        }
Exemplo n.º 2
0
        private async Task PasteHtmlFormat(DataPackageView dataPackageView)
        {
            var html = await dataPackageView.GetHtmlFormatAsync();

            var htmlFragment = HtmlFormatHelper.GetStaticFragment(html);
            await noteFieldView.HtmlEditor.InsertHtml(htmlFragment);
        }
Exemplo n.º 3
0
        //private void ShowSharedRtf(DataPackageView shareData)
        //{
        //    //throw new NotImplementedException();
        //}

        private async Task ShowSharedHtml(DataPackageView shareData)
        {
            DefaultViewModel["IsHtmlShared"]  = true;
            DefaultViewModel["IsHtmlLoading"] = true;

            var sharedHtmlContent = await shareData.GetHtmlFormatAsync();

            if (!String.IsNullOrEmpty(sharedHtmlContent))
            {
                // Convert the shared content that contains extra header data into just the working fragment
                var sharedHtmlFragment = HtmlFormatHelper.GetStaticFragment(sharedHtmlContent);

                // Reconcile any resource-mapped image references
                var sharedResourceMap = await shareData.GetResourceMapAsync();

                foreach (var resource in sharedResourceMap)
                {
                    var mappedImageElement     = String.Format("<img src={0}>", resource.Key);
                    var replacementImageBase64 = await resource.Value.Base64EncodeContent();

                    var replacementImageElement = String.Format("<img src='data:image/png;base64,{0}' />", replacementImageBase64);
                    var imageIndex = sharedHtmlFragment.IndexOf(mappedImageElement, StringComparison.Ordinal);
                    while (imageIndex >= 0)
                    {
                        sharedHtmlFragment = sharedHtmlFragment.Remove(imageIndex, mappedImageElement.Length);
                        sharedHtmlFragment = sharedHtmlFragment.Insert(imageIndex, replacementImageElement);
                        imageIndex         = sharedHtmlFragment.IndexOf(mappedImageElement, StringComparison.Ordinal);
                    }
                }

                DefaultViewModel["IsHtmlLoading"] = false;
                DefaultViewModel["SharedHtml"]    = sharedHtmlFragment;
            }
        }
Exemplo n.º 4
0
        async void PasteButton_Click(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.StatusMessage);
            OutputText.Text            = "Content in the clipboard: ";
            OutputResourceMapKeys.Text = "";
            OutputHtml.NavigateToString("<HTML></HTML>");

            var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();

            if (dataPackageView.Contains(StandardDataFormats.Text))
            {
                try
                {
                    var text = await dataPackageView.GetTextAsync();

                    OutputText.Text = "Text: " + Environment.NewLine + text;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Error retrieving Text format from Clipboard: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            else
            {
                OutputText.Text = "Text: " + Environment.NewLine + "Text format is not available in clipboard";
            }



            if (dataPackageView.Contains(StandardDataFormats.Html))
            {
                this.DisplayResourceMapAsync(dataPackageView);

                string htmlFormat = null;
                try
                {
                    htmlFormat = await dataPackageView.GetHtmlFormatAsync();
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Error retrieving HTML format from Clipboard: " + ex.Message, NotifyType.ErrorMessage);
                }

                if (htmlFormat != null)
                {
                    string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
                    OutputHtml.NavigateToString("HTML:<br/ > " + htmlFragment);
                }
            }
            else
            {
                OutputHtml.NavigateToString("HTML:<br/ > HTML format is not available in clipboard");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// The view page with mobile agent method.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private async void ViewMobile_OnClick(object sender, RoutedEventArgs e)
        {
            var handler = new HttpClientHandler {
                AllowAutoRedirect = true
            };
            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("user-agent", MobileUserAgent);
            var response = await client.GetAsync(new Uri(JeremyYogaPost));

            response.EnsureSuccessStatusCode();
            var html = await response.Content.ReadAsStringAsync();

            var fragment = HtmlFormatHelper.GetStaticFragment(HtmlFormatHelper.CreateHtmlFormat(html));

            this.WebViewControl.NavigateToString(fragment);
        }
Exemplo n.º 6
0
        private async Task FillCreateInfo(Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation shareOperation)
        {
            string rawHtml = shareOperation.Data.Contains(StandardDataFormats.Html) ? HtmlFormatHelper.GetStaticFragment((await shareOperation.Data.GetHtmlFormatAsync()).ToString()) : "";
            string rawText = (shareOperation.Data.Contains(StandardDataFormats.Text)) ? (await shareOperation.Data.GetTextAsync()).ToString() : "";
            string rawLink = (shareOperation.Data.Contains(StandardDataFormats.WebLink)) ? (await shareOperation.Data.GetWebLinkAsync()).ToString() : "";

            bool   htmlFormed = false;
            string Content    = string.Empty;
            string Caption    = string.Empty;

            if (!String.IsNullOrEmpty(rawHtml))
            {
                #region parsing html
                System.Text.StringBuilder contentBuilder = new System.Text.StringBuilder();

                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(rawHtml);

                var allDivs    = doc.DocumentNode.Descendants("div");
                var titleNodes = allDivs.Where(div => div.GetAttributeValue("class", "").Equals("snippet-info-title-div"));
                if (titleNodes.Count() > 0)
                {
                    Caption = titleNodes.First().Descendants("a").First().InnerHtml?.Trim();
                    contentBuilder.AppendLine("[" + Caption + "](" + rawLink + ")");
                }
                var imagesNodes = allDivs.Where(div => div.GetAttributeValue("class", "").Equals("snippet-images-div"));
                if (imagesNodes.Count() > 0)
                {
                    foreach (var imageNode in imagesNodes)
                    {
                        string imgUrl = imageNode.GetAttributeValue("src", "")?.Trim();
                        if (!String.IsNullOrEmpty(imgUrl))
                        {
                            contentBuilder.AppendLine("![](" + imgUrl + ")");
                        }
                    }
                }
                var descriptionNodes = allDivs.Where(div => div.GetAttributeValue("class", "").Equals("snippet-info-description-div"));
                if (descriptionNodes.Count() > 0)
                {
                    contentBuilder.AppendLine(descriptionNodes.First().InnerHtml?.Trim());
                }
                if (contentBuilder.Length > 0)
                {
                    htmlFormed = true;
                    Content    = contentBuilder.ToString();
                }
                #endregion
            }

            if (!htmlFormed)
            {
                Content = rawText;
                if (!String.IsNullOrEmpty(rawLink))
                {
                    Content = "[" + (String.IsNullOrEmpty(Content) ? "link" : Content) + "](" + rawLink + ")";
                }
            }

            mdOrganizer.Pages.ViewerPage.AutoCreateInfo = new Pages.AutoCreateInfo()
            {
                Caption = Caption,
                Content = Content
            };
        }
Exemplo n.º 7
0
        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;
                    }
                });
            });
        }
Exemplo n.º 8
0
        private async void DetectContents(ShareOperation shareOperation)
        {
            if (shareOperation.Data.Contains(StandardDataFormats.Uri))
            {
                var uri = await shareOperation.Data.GetUriAsync();

                if (uri != null)
                {
                }
            }

            if (shareOperation.Data.Contains(StandardDataFormats.Text))
            {
                string text = await shareOperation.Data.GetTextAsync();

                if (text != null)
                {
                }
            }

            if (shareOperation.Data.Contains(StandardDataFormats.StorageItems))
            {
                var storageItems = await shareOperation.Data.GetStorageItemsAsync();

                var fileList = String.Empty;
                for (var index = 0; index < storageItems.Count; index++)
                {
                    fileList += storageItems[index].Name;
                    if (index < storageItems.Count - 1)
                    {
                        fileList += ", ";
                    }
                }
            }

            if (shareOperation.Data.Contains(DataFormatName))
            {
                var receivedStrings = await shareOperation.Data.GetTextAsync(DataFormatName);

                JsonObject customObject = null;
                if (JsonObject.TryParse(receivedStrings, out customObject))
                {
                    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 = "Type: " + customObject["type"].Stringify();
                            JsonObject properties = customObject["properties"].GetObject();
                            receivedStrings += Environment.NewLine + "Image: " + properties["image"].Stringify()
                                               + Environment.NewLine + "Name: " + properties["name"].Stringify()
                                               + Environment.NewLine + "Book Format: " + properties["bookFormat"].Stringify()
                                               + Environment.NewLine + "Author: " + properties["author"].Stringify()
                                               + Environment.NewLine + "Number of Pages: " + properties["numberOfPages"].Stringify()
                                               + Environment.NewLine + "Publisher: " + properties["publisher"].Stringify()
                                               + Environment.NewLine + "Date Published: " + properties["datePublished"].Stringify()
                                               + Environment.NewLine + "In Language: " + properties["inLanguage"].Stringify()
                                               + Environment.NewLine + "ISBN: " + properties["isbn"].Stringify();
                        }
                    }
                }
            }

            if (shareOperation.Data.Contains(StandardDataFormats.Html))
            {
                var htmlFormat = await shareOperation.Data.GetHtmlFormatAsync();

                var htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
            }

            if (shareOperation.Data.Contains(StandardDataFormats.Bitmap))
            {
                var imageReceived = await shareOperation.Data.GetBitmapAsync();

                var stream = await imageReceived.OpenReadAsync();

                var bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
            }
        }
Exemplo n.º 9
0
        private static async Task <ReceivedShareItem> FetchDataFromPackageViewAsync(DataPackageView packageView)
        {
            var rval = new ReceivedShareItem()
            {
                Title                        = packageView.Properties.Title,
                Description                  = packageView.Properties.Description,
                PackageFamilyName            = packageView.Properties.PackageFamilyName,
                ContentSourceWebLink         = packageView.Properties.ContentSourceWebLink,
                ContentSourceApplicationLink = packageView.Properties.ContentSourceApplicationLink,
                LogoBackgroundColor          = packageView.Properties.LogoBackgroundColor,
            };

            if (packageView.Properties.Square30x30Logo != null)
            {
                using (var logoStream = await packageView.Properties.Square30x30Logo.OpenReadAsync())
                {
                    var logo = new MemoryStream();
                    await logoStream.AsStreamForRead().CopyToAsync(logo);

                    logo.Position = 0;
                    var str = Convert.ToBase64String(logo.ToArray());
                    //rval.Square30x30LogoBase64 = Convert.ToBase64String(logo.ToArray());
                    rval.Square30x30Logo = new Models.MemoryStreamBase64Item {
                        Base64String = str
                    };
                }
            }
            if (packageView.Properties.Thumbnail != null)
            {
                using (var thumbnailStream = await packageView.Properties.Thumbnail.OpenReadAsync())
                {
                    var thumbnail = new MemoryStream();
                    await thumbnailStream.AsStreamForRead().CopyToAsync(thumbnail);

                    thumbnail.Position = 0;
                    var str = Convert.ToBase64String(thumbnail.ToArray());
                    rval.Thumbnail = new Models.MemoryStreamBase64Item {
                        Base64String = str
                    };
                }
            }

            if (packageView.Contains(StandardDataFormats.WebLink))
            {
                try
                {
                    var link = new WebLinkShareItem
                    {
                        WebLink = await packageView.GetWebLinkAsync()
                    };

                    rval.AvialableShareItems.Add(link);
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            if (packageView.Contains(StandardDataFormats.ApplicationLink))
            {
                try
                {
                    var sharedApplicationLink = new ApplicationLinkShareItem
                    {
                        ApplicationLink = await packageView.GetApplicationLinkAsync()
                    };
                    rval.AvialableShareItems.Add(sharedApplicationLink);
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            if (packageView.Contains(StandardDataFormats.Text))
            {
                try
                {
                    var sharedText = new TextShareItem {
                        Text = await packageView.GetTextAsync()
                    };
                    rval.AvialableShareItems.Add(sharedText);
                    rval.Text = await packageView.GetTextAsync();

                    //rval.GetValueContainer(x => x.Text)
                    //      .GetNullObservable()
                    //	.Subscribe(e => sharedText.Text = rval.Text)
                    //	.DisposeWith(rval);
                    sharedText.GetValueContainer(x => x.Text)
                    .GetNullObservable()
                    .Subscribe(e => rval.Text = sharedText.Text)
                    .DisposeWith(rval);
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            if (packageView.Contains(StandardDataFormats.StorageItems))
            {
                try
                {
                    var files = await packageView.GetStorageItemsAsync();

                    var sharedStorageItem = new FilesShareItem
                    {
                        StorageFiles = new ObservableCollection <FileItem>()
                                       //StorageItems =
                    };
                    foreach (StorageFile sf in files)
                    {
                        var guidString = Guid.NewGuid().ToString();
                        StorageApplicationPermissions.FutureAccessList.AddOrReplace(guidString, sf, sf.Name);
                        var ts = await sf.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.VideosView);

                        var tmbs = new MemoryStream();
                        await ts.AsStreamForRead().CopyToAsync(tmbs);

                        var file = new FileItem
                        {
                            AccessToken  = guidString,
                            ContentType  = sf.ContentType,
                            FileName     = sf.DisplayName,
                            PossiblePath = sf.Path,
                            Thumbnail    = new Models.MemoryStreamBase64Item(tmbs.ToArray())
                        };

                        sharedStorageItem.StorageFiles.Add(file);
                    }
                    //StorageApplicationPermissions.FutureAccessList.AddOrReplace()

                    rval.AvialableShareItems.Add(sharedStorageItem);
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            //if (packageView.Contains(dataFormatName))
            //{
            //	try
            //	{
            //		this.sharedCustomData = await packageView.GetTextAsync(dataFormatName);
            //	}
            //	catch (Exception ex)
            //	{
            //		//NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
            //	}
            //}
            if (packageView.Contains(StandardDataFormats.Html))
            {
                var sharedHtmlFormatItem = new HtmlShareItem();
                var sharedHtmlFormat     = string.Empty;
                try
                {
                    sharedHtmlFormat = await packageView.GetHtmlFormatAsync();

                    //sharedHtmlFormatItem.HtmlFormat = sharedHtmlFormat;
                    sharedHtmlFormatItem.HtmlFragment = HtmlFormatHelper.GetStaticFragment(sharedHtmlFormat);
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
                //try
                //{
                //	var sharedResourceMap = await packageView.GetResourceMapAsync();
                //}
                //catch (Exception ex)
                //{
                //	//NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
                //}

                //if (packageView.Contains(StandardDataFormats.WebLink))
                //{
                //	try
                //	{
                //		sharedHtmlFormatItem.WebLink = await packageView.GetWebLinkAsync();
                //	}
                //	catch (Exception ex)
                //	{
                //		//NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                //	}
                //}
                rval.AvialableShareItems.Add(sharedHtmlFormatItem);
            }
            if (packageView.Contains(StandardDataFormats.Bitmap))
            {
                try
                {
                    var fi = await packageView.GetBitmapAsync();

                    using (var imgFileStream = await fi.OpenReadAsync())
                    {
                        var saveTargetStream = new InMemoryRandomAccessStream();

                        var bitmapSourceStream = imgFileStream;

                        await ServiceLocator
                        .Instance
                        .Resolve <IImageConvertService>()
                        .ConverterBitmapToTargetStreamAsync(bitmapSourceStream, saveTargetStream);

                        saveTargetStream.Seek(0);
                        var sr     = saveTargetStream.GetInputStreamAt(0);
                        var source = sr.AsStreamForRead();

                        var ms = new MemoryStream();
                        await source.CopyToAsync(ms);

                        var sharedBitmapStreamRef = new DelayRenderedImageShareItem
                        {
                            SelectedImage = new Models.MemoryStreamBase64Item(ms.ToArray())
                        };

                        rval.AvialableShareItems.Add(sharedBitmapStreamRef);
                    }
                }
                catch (Exception ex)
                {
                    //NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
            }

            //foreach (var item in rval.AvialableShareItems)
            //{
            //	//item.ContentSourceApplicationLink = rval.ContentSourceApplicationLink;
            //	//item.ContentSourceWebLink = rval.ContentSourceWebLink;
            //	//item.DefaultFailedDisplayText = rval.DefaultFailedDisplayText;
            //	//item.Description = rval.Description;
            //	//item.Title = rval.Title;
            //}
            return(rval);
        }
Exemplo n.º 10
0
        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();
                        }
                    }
                });
            });
        }
Exemplo n.º 11
0
        /// <summary>
        /// On ShareTarget activation we display the sahre source data
        /// Also we allow the user to choose what type of Note he would like to create and inside which notebook to created the new note.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public async Task ActivateAsync(ShareTargetActivatedEventArgs args)
        {
            var groups = NotesDataSource.GetGroups();

            if (groups.Count == 0)
            {
                Helpers.ShowMessageAsync("Please create notebook first.", "No Notebooks");
                Window.Current.Activate();
                return;
            }
            comboNotebooks.ItemsSource  = groups;
            comboNotebooks.SelectedItem = comboNotebooks.Items[0];

            var validNotes = System.Enum.GetValues(typeof(NoteTypes)).Cast <NoteTypes>();

            comboType.ItemsSource  = validNotes.Where(n => n != NoteTypes.Section && n != NoteTypes.Notebook);
            comboType.SelectedItem = comboType.Items[0];

            this.shareOperation = (args as ShareTargetActivatedEventArgs).ShareOperation;
            txtTitle.Text       = this.shareOperation.Data.Properties.Title;
            txtDescription.Text = this.shareOperation.Data.Properties.Description;

            if (this.shareOperation.Data.Contains(StandardDataFormats.WebLink))
            {
                Uri uri = await this.shareOperation.Data.GetWebLinkAsync();

                if (uri != null)
                {
                    txtDescription.Text = "Uri: " + uri.AbsoluteUri + Environment.NewLine;
                }
            }
            if (this.shareOperation.Data.Contains(StandardDataFormats.Text))
            {
                string text = await this.shareOperation.Data.GetTextAsync();

                if (text != null)
                {
                    txtDescription.Text += "Text: " + text + Environment.NewLine;
                }
            }
            if (this.shareOperation.Data.Contains(StandardDataFormats.StorageItems))
            {
                IReadOnlyList <IStorageItem> storageItems = null;
                storageItems = await this.shareOperation.Data.GetStorageItemsAsync();

                string fileList = String.Empty;
                for (int index = 0; index < storageItems.Count; index++)
                {
                    fileList += storageItems[index].Name;
                    if (index < storageItems.Count - 1)
                    {
                        fileList += ", ";
                    }
                }
                txtDescription.Text += "StorageItems: " + fileList + Environment.NewLine;
            }
            if (this.shareOperation.Data.Contains(StandardDataFormats.Html))
            {
                string htmlFormat = await this.shareOperation.Data.GetHtmlFormatAsync();

                string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
                txtDescription.Text += "Text: " + Windows.Data.Html.HtmlUtilities.ConvertToText(htmlFragment) + Environment.NewLine;
            }
            if (this.shareOperation.Data.Contains(StandardDataFormats.Bitmap))
            {
                img.Visibility = Visibility.Visible;
                IRandomAccessStreamReference imageReceived = await this.shareOperation.Data.GetBitmapAsync();

                var stream = await imageReceived.OpenReadAsync();

                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
                img.Source = bitmapImage;
            }

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