public SearchResultSuggestion(string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText) { if (text == null) throw new ArgumentNullException("text"); Text = text; DetailText = detailText; Tag = tag; Image = image; ImageAlternateText = imageAlternateText; }
/// <summary> /// Sets the contact image. If there is no image, we set a default one picked from our solution /// </summary> /// <param name="ThumbnailReference">Thumbnail reference of the contact from the contact store.</param> public async void SetImageAsync(IRandomAccessStreamReference ThumbnailReference) { var thumbnailImage = new BitmapImage(); if (ThumbnailReference != null) { using (IRandomAccessStreamWithContentType thumbnailStream = await ThumbnailReference.OpenReadAsync()) { thumbnailImage.SetSource(thumbnailStream); } } else { thumbnailImage = new BitmapImage(new Uri("ms-appx:///Assets/defaultContact.png", UriKind.Absolute)); } this.contactImage = thumbnailImage; }
async Task <BitmapImage> LoadImageAsync(IRandomAccessStreamReference thumbStreamReference) { m_profilePictureReadAsync = null; // Contact is not yet supported. throw new NotSupportedException("Contact is not yet supported"); //var operation = thumbStreamReference.OpenReadAsync(); //operation.Completed( // AsyncOperationCompletedHandler<IRandomAccessStreamWithContentType>( // [strongThis, completedFunction]( // IAsyncOperation<IRandomAccessStreamWithContentType> operation, // AsyncStatus asyncStatus) //{ // strongThis.m_dispatcherHelper.RunAsync( // [strongThis, asyncStatus, completedFunction, operation]() // { // BitmapImage bitmap; // // Handle the failure case here to ensure we are on the UI thread. // if (asyncStatus != AsyncStatus.Completed) // { // strongThis.m_profilePictureReadAsync = null); // return; // } // try // { // bitmap.SetSourceAsync(operation.GetResults()).Completed( // AsyncActionCompletedHandler( // [strongThis, completedFunction, bitmap](IAsyncAction, AsyncStatus asyncStatus) // { // if (asyncStatus != AsyncStatus.Completed) // { // strongThis.m_profilePictureReadAsync = null); // return; // } // completedFunction(bitmap); // strongThis.m_profilePictureReadAsync = null); // })); // } // catch (hresult_error &e) // { // strongThis.m_profilePictureReadAsync = null); // // Ignore the exception if the image is invalid // if (e.to_abi() == E_INVALIDARG) // { // return; // } // else // { // throw; // } // } // }); //})); //m_profilePictureReadAsync = operation; }
public async void LaunchApp(ApplicationExecutionState previousExecutionState) { DataSource = new KhanDataSource(); await DataSource.LoadAllData(); SearchPane searchPane = SearchPane.GetForCurrentView(); searchPane.PlaceholderText = "Search Khan Academy"; searchPane.QuerySubmitted += (sender, queryArgs) => { KhanAcademy.SearchResultsPage.Activate(queryArgs.QueryText, previousExecutionState); }; searchPane.SuggestionsRequested += (sender, suggestionArgs) => { var videos = App.DataSource.TopicGroups.SelectMany(g => g.Playlists.SelectMany(p => p.Videos.Where(v => Regex.IsMatch(v.Name ?? "", suggestionArgs.QueryText, RegexOptions.IgnoreCase) || Regex.IsMatch(v.Description ?? "", suggestionArgs.QueryText, RegexOptions.IgnoreCase)))) .Distinct(VideoItem.CreateComparer()) .Take(3); foreach (VideoItem vi in videos) { suggestionArgs.Request.SearchSuggestionCollection.AppendQuerySuggestion(vi.Title); } var recommended = App.DataSource.TopicGroups.SelectMany(g => g.Playlists.SelectMany(p => p.Videos.Where(v => Regex.IsMatch(v.Name ?? "", suggestionArgs.QueryText, RegexOptions.IgnoreCase)))).FirstOrDefault(); if (recommended != null) { suggestionArgs.Request.SearchSuggestionCollection.AppendSearchSeparator("Recommended"); IRandomAccessStreamReference imgStream = RandomAccessStreamReference.CreateFromUri(recommended.ImagePath); suggestionArgs.Request.SearchSuggestionCollection.AppendResultSuggestion(recommended.Title, recommended.Description, recommended.VideoPath.ToString(), imgStream, recommended.Title); } }; searchPane.ResultSuggestionChosen += (sender, resultArgs) => { var recommended = App.DataSource.TopicGroups.SelectMany(g => g.Playlists.SelectMany(p => p.Videos.Where(v => Regex.IsMatch(v.VideoPath.ToString() ?? "", resultArgs.Tag, RegexOptions.IgnoreCase)))).FirstOrDefault(); Frame f = Window.Current.Content as Frame; f.Navigate(typeof(VideoPage), JsonSerializer.Serialize(recommended)); }; if (previousExecutionState == ApplicationExecutionState.Running) { Window.Current.Activate(); return; } var rootFrame = new Frame(); SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (previousExecutionState == ApplicationExecutionState.Terminated) { await SuspensionManager.RestoreAsync(); } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(HubPage), JsonSerializer.Serialize(DataSource.TopicGroups))) { throw new Exception("Failed to create initial page"); } } // Place the frame in the current Window and ensure that it is active Window.Current.Content = rootFrame; Window.Current.Activate(); }
void ISearchSuggestionsRequest.AppendResultSuggestion( string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText ) { Contract.Requires<ArgumentNullException>( !string.IsNullOrEmpty( text ), "text" ); }
public BusStop(double latitude, double longitude, string title, string atcoCode = "", IRandomAccessStreamReference image = null) { var point = new BasicGeoposition() { Latitude = latitude, Longitude = longitude }; Point = point; Title = title; AtcoCode = atcoCode; Image = image; }
public void SetBitmap( IRandomAccessStreamReference value ) { // note: this would seem to be a flaw in the design. this should have been an interface all along. adapted.SetBitmap( (RandomAccessStreamReference) value ); }
public void Init(IRandomAccessStreamReference stream) { this.model = LearningModel.LoadFromStream(stream); this.session = new LearningModelSession(this.model); }
public static IAsyncOperation <OnnxModel> CreateFromStreamAsync(IRandomAccessStreamReference stream) { return(CreateFromStreamAsyncHelper(stream).AsAsyncOperation()); }
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(); } } }); }); }
/// <summary> /// Initializes a new instance of the <see cref="ChatMessageAttachment"/> class. /// </summary> /// <param name="mimeType">The MIME type of the attachment.</param> /// <param name="dataStreamReference">A stream containing the attachment data.</param> public ChatMessageAttachment(string mimeType, IRandomAccessStreamReference dataStreamReference) { this.MimeType = mimeType; this.DataStreamReference = dataStreamReference; }
/// <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(); }
private static async Task<IRandomAccessStreamReference> BitmapToPng(IRandomAccessStreamReference bitmap) { var rndAccessStreamWithContentType = await bitmap.OpenReadAsync(); var decoder = await BitmapDecoder.CreateAsync(rndAccessStreamWithContentType); var pixels = await decoder.GetPixelDataAsync(); var outStream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outStream); encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixels.DetachPixelData()); await encoder.FlushAsync(); return RandomAccessStreamReference.CreateFromStream(outStream); }
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 async void ShowProperties() { var selectedUser = (UserViewModel)UserList.SelectedValue; if (selectedUser != null) { ResultsText.Text = ""; ProfileImage.Source = null; rootPage.NotifyUser("", NotifyType.StatusMessage); try { User user = User.GetFromId(selectedUser.UserId); IBuffer aa = SystemIdentification.GetSystemIdForUser(user).Id; IBuffer bb = SystemIdentification.GetSystemIdForUser(null).Id; var aaS = SystemIdentification.GetSystemIdForUser(user).Id.ToArray(); var bbS = SystemIdentification.GetSystemIdForUser(null).Id.ToArray(); Debug.WriteLine("!!!" + aa + "~~~~~~~~~" + bb); // Start with some fixed properties. String result = "NonRoamableId: " + user.NonRoamableId + "\n"; result += "Type: " + user.Type.ToString() + "\n"; result += "AuthenticationStatus: " + user.AuthenticationStatus.ToString() + "\n"; // Build a list of all the properties we want. String[] desiredProperties = new String[] { KnownUserProperties.FirstName, KnownUserProperties.LastName, KnownUserProperties.ProviderName, KnownUserProperties.AccountName, KnownUserProperties.GuestHost, KnownUserProperties.PrincipalName, KnownUserProperties.DomainName, KnownUserProperties.SessionInitiationProtocolUri, }; // Issue a bulk query for all of the properties. IPropertySet values = await user.GetPropertiesAsync(desiredProperties); // Add those properties to our results. foreach (String property in desiredProperties) { result += property + ": " + values[property] + "\n"; } ResultsText.Text = result; // Get the user's picture. IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size64x64); if (streamReference != null) { IRandomAccessStream stream = await streamReference.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); ProfileImage.Source = bitmapImage; } } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } } }
public static async Task <WriteableBitmap> IRandomAccessStreamReferenceToWriteableBitmap(IRandomAccessStreamReference StreamRef) { if (StreamRef == null) { return(null); } IRandomAccessStreamWithContentType bitmapStream = await StreamRef.OpenReadAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(bitmapStream); WriteableBitmap writeableBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); writeableBitmap.SetSource(bitmapStream); return(writeableBitmap); }
protected override Task <DenseNetModel> GetModelFromStreamAsync(IRandomAccessStreamReference stream) => DenseNetModel.CreateFromStreamAsync(stream);
protected async override void OnNavigatedTo(NavigationEventArgs e) { // 获取分享激活 app 时的事件参数 ShareTargetActivatedEventArgs,可在 App.xaml.cs 的 override void OnShareTargetActivated(ShareTargetActivatedEventArgs args) 中拿到 ShareTargetActivatedEventArgs shareTargetActivated = e.Parameter as ShareTargetActivatedEventArgs; if (shareTargetActivated == null) { lblMsg.Text = "为了演示分享目标,请从分享源激活本程序"; return; } // 获取分享的 ShareOperation 对象 _shareOperation = shareTargetActivated.ShareOperation; // 异步获取分享数据 await Task.Factory.StartNew(async() => { // 显示分享数据的相关信息 OutputMessage("Title: " + _shareOperation.Data.Properties.Title); OutputMessage("Description: " + _shareOperation.Data.Properties.Description); OutputMessage("ApplicationName: " + _shareOperation.Data.Properties.ApplicationName); OutputMessage("PackageFamilyName: " + _shareOperation.Data.Properties.PackageFamilyName); OutputMessage("ApplicationListingUri: " + _shareOperation.Data.Properties.ApplicationListingUri); OutputMessage("ContentSourceApplicationLink: " + _shareOperation.Data.Properties.ContentSourceApplicationLink); OutputMessage("ContentSourceWebLink: " + _shareOperation.Data.Properties.ContentSourceWebLink); OutputMessage("LogoBackgroundColor: " + _shareOperation.Data.Properties.LogoBackgroundColor); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { IRandomAccessStreamWithContentType logoStream = await _shareOperation.Data.Properties.Square30x30Logo.OpenReadAsync(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(logoStream); imgLogo.Source = bitmapImage; }); OutputMessage(""); // 如果分享数据中包含 Text 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.Text)) { try { var text = await _shareOperation.Data.GetTextAsync(); OutputMessage("Text: " + text); } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含 WebLink 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.WebLink)) { try { var uri = await _shareOperation.Data.GetWebLinkAsync(); OutputMessage("WebLink: " + uri.AbsoluteUri); } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含 ApplicationLink 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.ApplicationLink)) { try { var uri = await _shareOperation.Data.GetApplicationLinkAsync(); OutputMessage("ApplicationLink: " + uri.AbsoluteUri); } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含 Bitmap 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.Bitmap)) { try { IRandomAccessStreamReference stream = await _shareOperation.Data.GetBitmapAsync(); ShowBitmap(stream); ShowThumbnail(_shareOperation.Data.Properties.Thumbnail); } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含 Html 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.Html)) { try { // 获取 html 数据 var html = await _shareOperation.Data.GetHtmlFormatAsync(); OutputMessage("Html: " + html); // 获取 html 中包含的本地资源的引用(如引用的本地图片等),其数据在分享源的 DataPackage.ResourceMap 中设置 IReadOnlyDictionary <string, RandomAccessStreamReference> sharedResourceMap = await _shareOperation.Data.GetResourceMapAsync(); } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含 StorageItems 格式数据,则显示之 if (_shareOperation.Data.Contains(StandardDataFormats.StorageItems)) { try { var storageItems = await _shareOperation.Data.GetStorageItemsAsync(); foreach (var storageItem in storageItems) { OutputMessage("storageItem: " + storageItem.Path); } } catch (Exception ex) { OutputMessage(ex.ToString()); } } // 如果分享数据中包含“http://webabcd/sharedemo”格式数据,则显示之 if (_shareOperation.Data.Contains("http://webabcd/sharedemo")) { try { var customData = await _shareOperation.Data.GetTextAsync("http://webabcd/sharedemo"); OutputMessage("Custom Data: " + customData); } catch (Exception ex) { OutputMessage(ex.ToString()); } } }); }
private async Task Attach(IRandomAccessStreamReference reference, string name) { if (Attachments.Count >= Board.MaxAttachments) return; var bitmap = new BitmapImage(); IRandomAccessStreamWithContentType stream = await reference.OpenReadAsync(); if (PostInfo.Files == null) { PostInfo.Files = new List<PostFileInfo>(); } var fileInfo = new PostFileInfo(name, reference); PostInfo.Files.Add(fileInfo); bitmap.SetSource(stream); Attachments.Add(new AttachmentViewModel { FileInfo = fileInfo, Image = bitmap, Type = stream.ContentType, }); }
public DownloadProgressVideoStreamingSession(IRandomAccessStreamReference streamRef, NicoVideoQuality requestQuality) { StreamRef = streamRef; Quality = requestQuality; }
public Task AttachPastedFile(IRandomAccessStreamReference reference) { return Attach(reference, Localization.GetForView("Posting", "Untitled")); }
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; } }); }); }
/// <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; } }); }); }
public async Task <MediaSource> RequestMusic(MusicModel model) { EventHandler <DownloadOperation> downloadProgressHandler = (o, e) => { _logger.Debug($"Downloading status of {model.Title}:\n\t{e.Progress.Status}, ({e.Progress.BytesReceived}/{e.Progress.TotalBytesToReceive})"); switch (e.Progress.Status) { case BackgroundTransferStatus.Completed: _utilityHelper.RunAtUIThread(() => model.HasCached = true); break; default: break; } }; IRandomAccessStreamReference ras = null; DownloadOperation downloadOperation = null; var downloadProgress = new Progress <DownloadOperation>(); downloadProgress.ProgressChanged += downloadProgressHandler; var cacheFile = await _createMusicFile(model); if (cacheFile == null) { var operations = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_backgroundDownloaderGroup); foreach (var item in operations) { if (item.ResultFile is StorageFile cachedFile) { if (cachedFile.Name == _utilityHelper.CreateMd5HashString(model.Title)) { downloadOperation = item; break; } } } if (downloadOperation != null) { ras = downloadOperation.GetResultRandomAccessStreamReference(); downloadOperation.AttachAsync().AsTask(downloadProgress); } else { _logger.Warning($"Don't find the downloading task for {model.Title}"); return(null); } } else { downloadOperation = _backgroundDownloader.CreateDownload(model.Uri, cacheFile); downloadOperation.IsRandomAccessRequired = true; ras = downloadOperation.GetResultRandomAccessStreamReference(); downloadOperation.StartAsync().AsTask(downloadProgress); } var source = MediaSource.CreateFromStreamReference(ras, "audio/mpeg"); return(source); }
public static async Task <FER_Emotion_RecognitionModel> CreateFromStreamAsync(IRandomAccessStreamReference stream) { FER_Emotion_RecognitionModel learningModel = new FER_Emotion_RecognitionModel(); learningModel.model = await LearningModel.LoadFromStreamAsync(stream); learningModel.session = new LearningModelSession(learningModel.model); learningModel.binding = new LearningModelBinding(learningModel.session); return(learningModel); }
public EmailAttachment(string fileName, IRandomAccessStreamReference data) { FileName = fileName; Data = data; }
public static async Task<WriteableBitmap> IRandomAccessStreamReferenceToWriteableBitmap(IRandomAccessStreamReference StreamRef) { if (StreamRef == null) return null; IRandomAccessStreamWithContentType bitmapStream = await StreamRef.OpenReadAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(bitmapStream); WriteableBitmap writeableBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); writeableBitmap.SetSource(bitmapStream); return writeableBitmap; }
void UpdateControlForContact(bool isNewContact) { Contact contact = Contact; if (contact == null) { // Explicitly setting to empty/null ensures the bound XAML is // correctly updated. m_contactDisplayNameInitials = ""; m_contactImageSource = null; UpdateIfReady(); return; } // It's possible for a second update to occur before the first finished loading // a profile picture (regardless of second having a picture or not). // Cancellation of any previously-activated tasks will mitigate race conditions. if (m_profilePictureReadAsync != null) { m_profilePictureReadAsync.Cancel(); } m_contactDisplayNameInitials = InitialsGenerator.InitialsFromContactObject(contact); // Order of preference (but all work): Large, Small, Source, Thumbnail IRandomAccessStreamReference thumbStreamReference = null; if (PreferSmallImage && contact.SmallDisplayPicture != null) { thumbStreamReference = contact.SmallDisplayPicture; } else { if (contact.LargeDisplayPicture != null) { thumbStreamReference = contact.LargeDisplayPicture; } else if (contact.SmallDisplayPicture != null) { thumbStreamReference = contact.SmallDisplayPicture; } else if (contact.SourceDisplayPicture != null) { thumbStreamReference = contact.SourceDisplayPicture; } else if (contact.Thumbnail != null) { thumbStreamReference = contact.Thumbnail; } } // If we have profile picture data available per the above, async load the picture from the platform. if (thumbStreamReference != null) { if (isNewContact) { // Prevent the case where context of a contact changes, but we show an old person while the new one is loaded. m_contactImageSource = null; } // The dispatcher is not available in design mode, so when in design mode bypass the call to LoadImageAsync. if (!SharedHelpers.IsInDesignMode()) { // Contact is not yet supported throw new NotSupportedException("Contact is not yet supported"); //LoadImageAsync( // thumbStreamReference, // [strongThis](BitmapImage profileBitmap) //{ // profileBitmap.DecodePixelType(DecodePixelType.Logical); // // We want to constrain the shorter side to the same dimension as the control, allowing the decoder to // // choose the other dimension without distorting the image. // if (profileBitmap.PixelHeight() < profileBitmap.PixelWidth()) // { // profileBitmap.DecodePixelHeight((int)(strongThis.Height())); // } // else // { // profileBitmap.DecodePixelWidth((int)(strongThis.Width())); // } // strongThis.m_contactImageSource = ImageSource(profileBitmap)); // strongThis.UpdateIfReady(); //}); } } else { // Else clause indicates that (Contact.Thumbnail == null). m_contactImageSource = null; } UpdateIfReady(); }
/// <summary> /// Read the image (QR-code) from the clipboard /// </summary> public async Task ReadQRCodeFromClipboard() { DataPackageView dataPackageView = Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.Bitmap)) { IRandomAccessStreamReference imageReceived = null; try { imageReceived = await dataPackageView.GetBitmapAsync(); } catch (Exception ex) { Logger.Log(ex.Message, Category.Exception, Priority.Medium); } finally { try { if (imageReceived != null) { using IRandomAccessStreamWithContentType imageStream = await imageReceived.OpenReadAsync(); BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageStream); SoftwareBitmap softwareBitmap = await bitmapDecoder.GetSoftwareBitmapAsync(); string result = ReadQRCodeFromBitmap(softwareBitmap); _qrCodeStr = HttpUtility.UrlDecode(result); if (!string.IsNullOrEmpty(_qrCodeStr)) { //clear the clipboard, if the image is read as TOTP Clipboard.Clear(); ParseQRCode(); //move to the input dialog SelectedPivotIndex = 1; if (!string.IsNullOrEmpty(SecretKey) && !string.IsNullOrEmpty(Model.Issuer)) /* && !string.IsNullOrEmpty(Model.Label)*/ { IsPrimaryBTNEnable = true; } else { MessageDialog dialog = new MessageDialog(ResourceService.GetLocalizedString("AddAccountContentDialogQRCodeContentError"), Strings.Resources.Error); await dialog.ShowAsync(); //move to the selection dialog SelectedPivotIndex = 0; } } else { MessageDialog dialog = new MessageDialog(ResourceService.GetLocalizedString("AddAccountContentDialogQRCodeContentError"), Strings.Resources.Error); await dialog.ShowAsync(); } } else { //TODO add error: empty Clipboard? } } catch (Exception) { // TODO error by processing the image throw; } } } }
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; } }); }); }
//康戳键 private void KeyCtrl(VirtualKey value) { switch (value) { //Undo:撤销 case VirtualKey.Z: if (App.Model.isUndo) { Undo(); } break; case VirtualKey.Y: if (App.Model.isRedo) { Redo(); } break; case VirtualKey.S: HomeContentDialog.ShowAsync(); break; //Mask:选区 case VirtualKey.X: 修图.Control.MaskButton.Cut(); break; case VirtualKey.C: 修图.Control.MaskButton.Copy(); break; case VirtualKey.V: DataPackageView dataPackageView = Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.Bitmap)) { IRandomAccessStreamReference imageReceived = null; imageReceived = dataPackageView.GetBitmapAsync().AsTask().Result; if (imageReceived != null) { using (IRandomAccessStream stream = imageReceived.OpenReadAsync().AsTask().Result) { App.Model.SecondCanvasBitmap = CanvasVirtualBitmap.LoadAsync(App.Model.VirtualControl, stream).AsTask().Result; App.InitializeOther(); LayerControl_Layers(); } } } else if (App.Model.isClipboard == true) { App.InitializeEffect(); MaskButton_Mask(102); } break; case VirtualKey.Delete: 修图.Control.MaskButton.Clear(); break; case VirtualKey.E: 修图.Control.MaskButton.Extract(); break; case VirtualKey.M: 修图.Control.MaskButton.Merge(); break; case VirtualKey.A: 修图.Control.MaskButton.All(); break; case VirtualKey.D: 修图.Control.MaskButton.Deselect(); break; case VirtualKey.P: 修图.Control.MaskButton.Pixel(); break; case VirtualKey.I: 修图.Control.MaskButton.Invert(); break; case VirtualKey.F: MaskButton_Mask(110); break; case VirtualKey.T: MaskButton_Mask(111); break; } }