public ImageViewerPage()
        {
            InitializeComponent();
            DataTransferManager.GetForCurrentView().DataRequested += (s, e) =>
            {
                e.Request.Data.Properties.Title = "分享自iV2EX";
                e.Request.Data.SetText(_imageUrl);
                e.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(_file));
            };
            var share = Observable.FromEventPattern <RoutedEventArgs>(ShareImage, nameof(ShareImage.Click))
                        .ObserveOnCoreDispatcher()
                        .Subscribe(x =>
            {
                if (DataTransferManager.IsSupported())
                {
                    DataTransferManager.ShowShareUI();
                }
            });
            var save = Observable.FromEventPattern <RoutedEventArgs>(SaveImage, nameof(SaveImage.Click))
                       .ObserveOnCoreDispatcher()
                       .Subscribe(async x =>
            {
                try
                {
                    var library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
                    var path    = await library.SaveFolder.CreateFolderAsync("iV2EX",
                                                                             CreationCollisionOption.OpenIfExists);
                    await _file.CopyAsync(path, _file.Name + Path.GetExtension(_imageUrl),
                                          NameCollisionOption.ReplaceExisting);
                    ToastTips.ShowTips("已经保存到图片库");
                }
                catch
                {
                    ToastTips.ShowTips("保存失败");
                }
            });
            var menu = Observable.FromEventPattern <TappedRoutedEventArgs>(MenuItemPanel, nameof(MenuItemPanel.Tapped))
                       .ObserveOnCoreDispatcher()
                       .Subscribe(x => MenuItemPanel.ContextFlyout.ShowAt(MenuItemPanel));

            _events = new List <IDisposable> {
                share, save, menu
            };
        }
示例#2
0
        private void UpdateTransportControls(SongMetadata songMetadata)
        {
            if (songMetadata == null)
            {
                return;
            }

            try
            {
                var updater = NepApp.MediaPlayer.MediaTransportControls.DisplayUpdater;
                updater.Type = MediaPlaybackType.Music;
                updater.MusicProperties.Title  = songMetadata.Track;
                updater.MusicProperties.Artist = songMetadata.Artist;
                updater.AppMediaId             = songMetadata.StationPlayedOn.GetHashCode().ToString();

                if (songMetadata.StationLogo != null)
                {
                    updater.Thumbnail = RandomAccessStreamReference.CreateFromUri(songMetadata.StationLogo);
                }

                if (songMetadata is ExtendedSongMetadata)
                {
                    var extended = (ExtendedSongMetadata)songMetadata;

                    //add album title and album artist information if it is available
                    if (extended.Album != null)
                    {
                        updater.MusicProperties.AlbumTitle  = extended.Album?.Album ?? "";
                        updater.MusicProperties.AlbumArtist = extended.Album?.Artist ?? "";
                    }
                }
                else
                {
                    updater.MusicProperties.AlbumTitle  = "";
                    updater.MusicProperties.AlbumArtist = "";
                }

                updater.Update();
            }
            catch (COMException) { }
            catch (Exception)
            {
            }
        }
        private async void SetArtworkThumbnail(byte[] data)
        {
            if (artworkStream != null)
            {
                artworkStream.Dispose();
            }
            if (data == null)
            {
                artworkStream            = null;
                displayUpdater.Thumbnail = null;
            }
            else
            {
                artworkStream = new InMemoryRandomAccessStream();
                await artworkStream.WriteAsync(data.AsBuffer());

                displayUpdater.Thumbnail = RandomAccessStreamReference.CreateFromStream(artworkStream);
            }
        }
        private void OnAddPin(MyPin pin)
        {
            var pinPosition = new BasicGeoposition
            {
                Latitude  = pin.Coordinate.Latitude,
                Longitude = pin.Coordinate.Longitude
            };
            var pinPoint = new Geopoint(pinPosition);
            var mapIcon  = new MapIcon
            {
                Image = RandomAccessStreamReference.CreateFromUri(new Uri($"ms-appx:///{pin.IconPath}")),
                CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible,
                Location = pinPoint,
                NormalizedAnchorPoint = new Point(0.5, 1.0),
                Title = pin.Label
            };

            _nativeMap.MapElements.Add(mapIcon);
        }
示例#5
0
        //分享
        private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            DataRequest request     = e.Request;
            DataPackage requestData = request.Data;

            requestData.Properties.Title = sharetitle;
            requestData.SetText(sharedetail + sharedate);

            // Because we are making async calls in the DataRequested event handler,
            //  we need to get the deferral first.
            DataRequestDeferral deferral = request.GetDeferral();

            // Make sure we always call Complete on the deferral.
            try {
                requestData.SetBitmap(RandomAccessStreamReference.CreateFromFile(shareimg));
            } finally {
                deferral.Complete();
            }
        }
示例#6
0
        void OnShareDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataRequest request = args.Request;

            request.Data.Properties.Title       = App.title;
            request.Data.Properties.Description = App.details;
            DataRequestDeferral deferal = request.GetDeferral();

            /* List<IStorageItem> imageItems = new List<IStorageItem> { App._tempExportFile };
             * request.Data.SetStorageItems(imageItems);
             *
             * RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(App._tempExportFile);
             * request.Data.Properties.Thumbnail = imageStreamRef;
             * request.Data.SetBitmap(imageStreamRef);
             */
            request.Data.SetText(App.details);
            request.Data.SetBitmap(RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/background1.jpg")));
            deferal.Complete();
        }
示例#7
0
        async void ReportCompleted_Click(object sender, RoutedEventArgs e)
        {
            if (AddQuickLink.IsChecked.Equals(true))
            {
                QuickLink quickLinkInfo = new QuickLink
                {
                    Id    = QuickLinkId.Text,
                    Title = QuickLinkTitle.Text,

                    // For QuickLinks, the supported FileTypes and DataFormats are set independently from the manifest.
                    SupportedFileTypes   = { "*" },
                    SupportedDataFormats =
                    {
                        StandardDataFormats.Text,
                        StandardDataFormats.WebLink,
                        StandardDataFormats.ApplicationLink,
                        StandardDataFormats.Bitmap,
                        StandardDataFormats.StorageItems,
                        StandardDataFormats.Html,
                        dataFormatName
                    }
                };

                try
                {
                    StorageFile iconFile = await Package.Current.InstalledLocation.CreateFileAsync("assets\\user.png", CreationCollisionOption.OpenIfExists);

                    quickLinkInfo.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile);
                    this.shareOperation.ReportCompleted(quickLinkInfo);
                }
                catch (Exception)
                {
                    // Even if the QuickLink cannot be created it is important to call ReportCompleted. Otherwise, if this is a long-running share,
                    // the app will stick around in the long-running share progress list.
                    this.shareOperation.ReportCompleted();
                    throw;
                }
            }
            else
            {
                this.shareOperation.ReportCompleted();
            }
        }
示例#8
0
        private async void CTRL_Map_Main_MapElementClick(Windows.UI.Xaml.Controls.Maps.MapControl sender, MapElementClickEventArgs args)
        {
            if (args.MapElements.Count < 1 || args.MapElements[0] == null)
            {
                return;
            }

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                                                                                        () =>
            {
                MapIcon selectedMapIcon = args.MapElements.FirstOrDefault(x => x is MapIcon) as MapIcon;

                if (selectedMapIcon is null)
                {
                    var clickedProjectName = args.MapElements[0].Tag.ToString();
                    var position           = args.Location.Position;

                    var minLengthSufix = Math.Min(clickedProjectName.Length, 3);
                    var length         = 16;
                    var datetime       = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
                    var projectName    = clickedProjectName.Substring(0, minLengthSufix).ToUpper(CultureInfo.InvariantCulture);
                    var deviceID       = projectName + datetime.Substring(datetime.Length - length, length);


                    AddPushpin(deviceID, position);

                    CTRL_NewDevices.AddDevice(deviceID, deviceID, position);
                }
                else
                {
                    string tag = selectedMapIcon.Tag.ToString();

                    if (tag.Equals("NEW"))
                    {
                        return;
                    }

                    selectedMapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(resourceLoader.GetString("Map_Pushpin_Red")));

                    CTRL_Telemetry.AddDevice(selectedMapIcon.Title, selectedMapIcon.Title, selectedMapIcon.Location.Position);
                }
            });
        }
示例#9
0
        /*
         * 程序间通信
         */
        private async void OnShareRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataPackage data = args.Request.Data;

            if (currentWeatherBlock.Text != "")
            {
                data.Properties.Title       = "天气实况";
                data.Properties.Description = currentWeatherBlock.Text;
                data.SetText(currentWeatherBlock.Text);
                StorageFile imageFile = await Package.Current.InstalledLocation.GetFileAsync("Assets\\background.jpg");

                data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(imageFile);
                data.SetBitmap(RandomAccessStreamReference.CreateFromFile(imageFile));
            }
            else
            {
                var i = new MessageDialog("无可用分享").ShowAsync();
            }
        }
示例#10
0
        public override MapElement CreateShape(object viewModel, Geopath path)
        {
            var icon = new MapIcon {
                Location = new Geopoint(path.Positions[0]),
                NormalizedAnchorPoint = new Point(AnchorX, AnchorY), ZIndex = ZIndex
            };

            if (!string.IsNullOrWhiteSpace(Title))
            {
                icon.Title = Title;
            }

            if (!string.IsNullOrWhiteSpace(ImageUri))
            {
                icon.Image = RandomAccessStreamReference.CreateFromUri(new Uri(ImageUri));
            }

            return(icon);
        }
        protected override bool GetShareContent(DataRequest request)
        {
            bool succeeded = false;

            if (this.selectedImage != null)
            {
                DataPackage requestData = request.Data;
                requestData.Properties.Title       = "Delay rendered image";
                requestData.Properties.Description = "Resized image from the Share Source sample";
                requestData.Properties.Thumbnail   = RandomAccessStreamReference.CreateFromFile(this.selectedImage);
                requestData.SetDataProvider(StandardDataFormats.Bitmap, providerRequest => this.OnDeferredImageRequestedHandler(providerRequest, this.selectedImage));
                succeeded = true;
            }
            else
            {
                request.FailWithDisplayText("Select an image you would like to share and try again.");
            }
            return(succeeded);
        }
示例#12
0
        private void BuildMediaPlaybackList()
        {
            for (int i = 1; i < 5; i++)
            {
                string file = $"ms-appx:///Assets/mp3/0{i}.mp3";

                MediaSource                source          = MediaSource.CreateFromUri(new Uri(file, UriKind.RelativeOrAbsolute));
                MediaPlaybackItem          item            = new MediaPlaybackItem(source);
                MediaItemDisplayProperties displayProperty = item.GetDisplayProperties();
                displayProperty.Type = MediaPlaybackType.Music;
                displayProperty.MusicProperties.Title       = $"0{i}.mp3";
                displayProperty.MusicProperties.AlbumArtist = "JJ";
                displayProperty.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri($"ms-appx:///Assets/mp3/0{i}.jpg", UriKind.RelativeOrAbsolute));
                item.ApplyDisplayProperties(displayProperty);

                PlaybackList.Add(new MediaPlaybackItemDataWrapper(item));
                MediaPlaybackList.Items.Add(item);
            }
        }
示例#13
0
        private async void MapTapped(MapControl sender, MapInputEventArgs args)
        {
            var dialog = new Windows.UI.Popups.MessageDialog("Agregar este lugar");

            dialog.Commands.Add(new Windows.UI.Popups.UICommand("Aceptar")
            {
                Id = 1
            });
            dialog.Commands.Add(new Windows.UI.Popups.UICommand("Cancelar")
            {
                Id = 0
            });
            var result = await dialog.ShowAsync();

            if (result.Id.Equals(1))
            {
                var res = await contentDialog.ShowAsync();

                crearLugar            = 1;
                progressRing.IsActive = true;
                BasicGeoposition pos = new BasicGeoposition()
                {
                    Latitude = args.Location.Position.Latitude, Longitude = args.Location.Position.Longitude
                };;
                Geopoint point = new Geopoint(pos);

                MapLocationFinderResult LocationAdress = await MapLocationFinder.FindLocationsAtAsync(point);

                string direccion = LocationAdress.Locations[0].Address.Street + "-" + LocationAdress.Locations[0].Address.StreetNumber + ", "
                                   + LocationAdress.Locations[0].Address.Country + ", " + LocationAdress.Locations[0].Address.Town;


                MapIcon mapIcon = new MapIcon();
                mapIcon.Location = point;
                mapIcon.NormalizedAnchorPoint = new Point(0.5, 1.0);
                mapIcon.Title  = titulo_lugar + " - " + direccion;
                mapIcon.Image  = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/bus.png"));
                mapIcon.ZIndex = 0;

                mapControl.MapElements.Add(mapIcon);
                progressRing.IsActive = false;
            }
        }
示例#14
0
        private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            DataRequest request     = e.Request;
            DataPackage requestData = request.Data;

            requestData.Properties.Title = sharename;
            requestData.SetText("歌手:" + shareartist + "\n" + "专辑:" + sharealbum + "\n" + "链接:" + shareurl);

            DataRequestDeferral deferral = request.GetDeferral();

            try
            {
                requestData.SetBitmap(RandomAccessStreamReference.CreateFromFile(shareimag));
            }
            finally
            {
                deferral.Complete();
            }
        }
示例#15
0
        private async void InitializeData()
        {
            loadGoal();

            goaltextbox.Text = goal.ToString();

            accessStatus = await Geolocator.RequestAccessAsync();

            if (accessStatus == GeolocationAccessStatus.Allowed)
            {
                gl = new Geolocator()
                {
                    MovementThreshold = 5, DesiredAccuracyInMeters = 5, ReportInterval = 1000
                };
                pos = await gl.GetGeopositionAsync();

                curPoint = new MapIcon()
                {
                    NormalizedAnchorPoint = new Point(0.5, 0.5),
                    Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/LocationLogo.png")),
                    ZIndex   = 2,
                    Location = pos.Coordinate.Point
                };
                gpList = new List <Geoposition>()
                {
                    pos
                };
                bgpList = new List <BasicGeoposition>()
                {
                    pos.Coordinate.Point.Position
                };
                line = new MapPolyline()
                {
                    StrokeThickness = 2,
                    StrokeColor     = ((SolidColorBrush)Resources["SystemControlHighlightAccentBrush"]).Color,
                    ZIndex          = 1,
                    Path            = new Geopath(bgpList)
                };
                map.MapElements.Add(curPoint);
                track = false;
                gl.PositionChanged += OnPositionChanged;
            }
        }
示例#16
0
        public async void Send(string phoneNumber, string messageBody, StorageFile attachmentFile, string mimeType)
        {
            var chat = new ChatMessage {
                Body = messageBody
            };

            if (attachmentFile != null)
            {
                var stream = RandomAccessStreamReference.CreateFromFile(attachmentFile);

                var attachment = new ChatMessageAttachment(mimeType, stream);

                chat.Attachments.Add(attachment);
            }

            chat.Recipients.Add(phoneNumber);

            await ChatMessageManager.ShowComposeSmsMessageAsync(chat);
        }
示例#17
0
        public static async void LoadAppLayout(string name, LoadLayout t)
        {
            Uri u = new Uri("ms-appx:///Maps/" + name);
            RandomAccessStreamReference rass = RandomAccessStreamReference.CreateFromUri(u);
            IRandomAccessStream         ir   = await rass.OpenReadAsync();

            Stream s = ir.AsStream();

            byte[] buff = new byte[s.Length];
            s.Read(buff, 0, buff.Length);
            int c = buff.Length / 4096;

            LayOut[] l = new LayOut[c];
            for (int i = 0; i < c; i++)
            {
                l[i] = LoadLayout(ref buff, i * 4096);
            }
            t(l);
        }
示例#18
0
        async private void CopyBitmap(bool isDelayRendered)
        {
            var imagePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter         = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
            };

            var imageFile = await imagePicker.PickSingleFileAsync();

            if (imageFile != null)
            {
                var dataPackage = new DataPackage();

                // Use one click handler for two operations: regular copy and copy using delayed rendering
                // Differentiate the case by the button name
                if (isDelayRendered)
                {
                    dataPackage.SetDataProvider(StandardDataFormats.Bitmap, request => OnDeferredImageRequestedHandler(request, imageFile));
                    OutputText.Text = "Image has been copied using delayed rendering";
                }
                else
                {
                    dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromFile(imageFile));
                    OutputText.Text = "Image has been copied";
                }

                try
                {
                    Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
                }
                catch (Exception ex)
                {
                    // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
                    rootPage.NotifyUser("Error copying content to Clipboard: " + ex.Message + ". Try again", NotifyType.ErrorMessage);
                }
            }
            else
            {
                OutputText.Text = "No image was selected.";
            }
        }
示例#19
0
        void BitmapRequested(CustomMapTileDataSource sender, MapTileBitmapRequestedEventArgs args)
        {
            var deferral = args.Request.GetDeferral();
            IRandomAccessStreamReference referenceStream;
            double lat, lon = 0;
            int    pixelX, pixelY = 0;

            Microsoft.MapPoint.TileSystem.TileXYToPixelXY(args.X, args.Y, out pixelX, out pixelY);
            Microsoft.MapPoint.TileSystem.PixelXYToLatLong(pixelX, pixelY, args.ZoomLevel, out lat, out lon);
            BasicGeoposition northWest = new BasicGeoposition {
                Latitude = lat, Longitude = lon
            };

            Microsoft.MapPoint.TileSystem.PixelXYToLatLong(pixelX + (int)sizeOfMapTile, pixelY + (int)sizeOfMapTile, args.ZoomLevel, out lat, out lon);
            BasicGeoposition southEast = new BasicGeoposition {
                Latitude = lat, Longitude = lon
            };
            GeoboundingBox tileBox = new GeoboundingBox(northWest, southEast);

            if (tileBox.CollidesWith(PathBox))
            {
                if (PathCache.pointInPolygon(northWest.Longitude, northWest.Latitude) &&
                    PathCache.pointInPolygon(southEast.Longitude, southEast.Latitude) &&
                    PathCache.pointInPolygon(northWest.Longitude, southEast.Latitude) &&
                    PathCache.pointInPolygon(southEast.Longitude, northWest.Latitude))
                {
                    referenceStream = RandomAccessStreamReference.CreateFromStream(InTile);
                }
                else
                {
                    var cutter = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                    cutTile(cutter, pixelX, pixelY, args.ZoomLevel);
                    referenceStream = RandomAccessStreamReference.CreateFromStream(cutter);
                }
            }
            else
            {
                referenceStream = RandomAccessStreamReference.CreateFromStream(OutTile);
            }

            args.Request.PixelData = referenceStream;
            deferral.Complete();
        }
示例#20
0
 private void AddPointsOfInterest()
 {
     foreach (var poi in route.RoutePoints)
     {
         var point = poi as PointOfInterest;
         if (point != null)
         {
             var icon = new MapIcon
             {
                 Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Point.png")),
                 Title    = point.Title[(int)_language],
                 Location = poi.Location,
                 NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0)
             };
             Map.MapElements.Add(icon);
             _routeIcons.Add(point, icon);
         }
     }
 }
        void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            //Assemble text to be shared
            var item = (BreedDataItem)this.itemGridView.SelectedItem;

            request.Data.Properties.Title       = item.Group.Title;
            request.Data.Properties.Description = "Breed size and description";
            var breedSize = "\r\nBreed Size Description\r\n";

            breedSize += String.Join("\r\n", item.Group.Description);
            request.Data.SetText(breedSize);

            //Share image to accompany text
            var reference = RandomAccessStreamReference.CreateFromUri(new Uri(item.Group.ImagePath.AbsoluteUri));

            request.Data.Properties.Thumbnail = reference;
            request.Data.SetBitmap(reference);
        }
        public void OnDataRequested(DataRequest request)
        {
            request.Data.Properties.Title = ViewModel.CurrentSkinName;
            request.Data.SetWebLink(ViewModel.CurrentSkinUri);

            DataRequestDeferral deferral = request.GetDeferral();

            try
            {
                RandomAccessStreamReference streamReference = RandomAccessStreamReference.CreateFromUri(ViewModel.CurrentSkinUri);

                request.Data.Properties.Thumbnail = streamReference;
                request.Data.SetBitmap(streamReference);
            }
            finally
            {
                deferral.Complete();
            }
        }
示例#23
0
 private static async void Player_SourceChanged(MediaPlayer sender, object args)
 {
     if (List.Count <= NowPlaying)
     {
         return;
     }
     //当加载一个新的播放文件时,此时你应当加载歌词和SMTC
     //加载SMTC
     ControlsDisplayUpdater.Type = MediaPlaybackType.Music;
     ControlsDisplayUpdater.MusicProperties.Artist     = NowPlayingItem.AudioInfo.Artist;
     ControlsDisplayUpdater.MusicProperties.AlbumTitle = NowPlayingItem.AudioInfo.Album;
     ControlsDisplayUpdater.MusicProperties.Title      = NowPlayingItem.AudioInfo.SongName;
     //因为加载图片可能会高耗时,所以在此处加载
     Invoke(() => OnPlayItemChange?.Invoke(NowPlayingItem));
     //加载歌词
     LoadLyrics(NowPlayingItem);
     ControlsDisplayUpdater.Thumbnail = NowPlayingItem.isOnline ? RandomAccessStreamReference.CreateFromUri(new Uri(NowPlayingItem.NcPlayItem.Album.cover)) : RandomAccessStreamReference.CreateFromStream(await NowPlayingItem.AudioInfo.LocalSongFile.GetThumbnailAsync(ThumbnailMode.MusicView, 9999));
     ControlsDisplayUpdater.Update();
 }
示例#24
0
        private void DataTransferManagerOnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataPackage data = args.Request.Data;

            data.Properties.Title = _shareItem.Title;
            if (_shareItem.Message != null)
            {
                data.Properties.Description = _shareItem.Message;
            }
            if (_shareItem.ImageUri != null)
            {
                data.SetBitmap(RandomAccessStreamReference.CreateFromUri(_shareItem.ImageUri));
            }
            if (_shareItem.Link != null)
            {
                data.SetUri(_shareItem.Link);
            }
            _dataTransferManager.DataRequested -= DataTransferManagerOnDataRequested;
        }
示例#25
0
        private async void GetShareContent(DataRequest request)
        {
            var         item        = flipView.SelectedItem as NatGeoImage;
            DataPackage requestData = request.Data;

            requestData.Properties.Title       = item.Title;
            requestData.Properties.Description = item.Description; // The description is optional.
            requestData.SetUri(new Uri(item.DownloadUrl ?? item.ImageUrl));

            // It's recommended to use both SetBitmap and SetStorageItems for sharing a single image
            // since the target app may only support one or the other.
            var client = new HttpClient();
            var r      = new HttpRequestMessage(
                HttpMethod.Get, item.DownloadUrl ?? item.ImageUrl);
            HttpResponseMessage response = await client.SendAsync(r,
                                                                  HttpCompletionOption.ResponseHeadersRead);


            StorageFile imageFile =
                await
                ApplicationData.Current.LocalFolder.CreateFileAsync("download.jpg",
                                                                    CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);

            var writer = new DataWriter(fs.GetOutputStreamAt(0));

            writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();

            writer.DetachStream();
            await fs.FlushAsync();

            var imageItems = new List <IStorageItem>();

            imageItems.Add(imageFile);
            requestData.SetStorageItems(imageItems);

            RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(imageFile);

            requestData.Properties.Thumbnail = imageStreamRef;
            requestData.SetBitmap(imageStreamRef);
        }
        public MapView()
        {
            this.InitializeComponent();
            MapControl.MapServiceToken = keysLoader.GetString(Constants.MapServiceTokenKeyName);
            MapService.ServiceToken    = MapControl.MapServiceToken;

            _userLocation = new MapIcon
            {
                Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/UserLocation.png")),
                Title = "Your Location",
                NormalizedAnchorPoint = new Point(0.5, 0.5)
            };

            if (!Core.IsUserLoggedIn())
            {
                AddNewButton.Visibility = Visibility.Collapsed;
                LogoutButton.Visibility = Visibility.Collapsed;
            }
        }
示例#27
0
        //Insert the M3_DataRequested snippet here

        private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;

            request.Data.Properties.Title       = $"I'm visiting the {CurrentSight.Name}";
            request.Data.Properties.Description = $"{CurrentSight.Description}";
            request.Data.SetText($"{CurrentSight.Description}");

            var    localImage  = SightImage.UriSource.AbsoluteUri;
            string htmlPayload = $"<img src=\"{localImage}\" width=\"200\"/><p>{CurrentSight.Description}</p>";
            var    htmlFormat  = HtmlFormatHelper.CreateHtmlFormat(htmlPayload);

            request.Data.SetHtmlFormat(htmlFormat);

            // Because the HTML contains a local image, we need to add it to the ResourceMap.
            var streamRef = RandomAccessStreamReference.CreateFromUri(new Uri(localImage));

            request.Data.ResourceMap[localImage] = streamRef;
        }
示例#28
0
        private MediaPlaybackItem ToPlaybackItem(Song song)
        {
            var source = MediaSource.CreateFromUri(new Uri(song.StreamUrl));

            var playbackItem = new MediaPlaybackItem(source);

            var displayProperties = playbackItem.GetDisplayProperties();

            displayProperties.Type = Windows.Media.MediaPlaybackType.Music;
            displayProperties.MusicProperties.Title  = song.Title;
            displayProperties.MusicProperties.Artist = song.Artist;
            displayProperties.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(song.AlbumArt));

            playbackItem.ApplyDisplayProperties(displayProperties);

            source.CustomProperties[MediaItemIdKey] = song.ItemId;

            return(playbackItem);
        }
示例#29
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="scenarioPage">The scenario page constructing us</param>
        public PrintHelper(string jobName)
        {
            JobName = jobName;

            printPreviewPages = new List <UIElement>();
            // Start these tasks early because we know we're going to need the
            // streams in PrintTaskRequested.
            RandomAccessStreamReference wideMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Forms9Patch.UWP/Assets/wideMargins.svg"));

            wideMarginsIconTask = wideMarginsIconReference.OpenReadAsync().AsTask();

            RandomAccessStreamReference moderateMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Forms9Patch.UWP/Assets/moderateMargins.svg"));

            moderateMarginsIconTask = moderateMarginsIconReference.OpenReadAsync().AsTask();

            RandomAccessStreamReference narrowMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Forms9Patch.UWP/Assets/narrowMargins.svg"));

            narrowMarginsIconTask = narrowMarginsIconReference.OpenReadAsync().AsTask();
        }
示例#30
0
 public static async Task AddTags(IStorageFile resultFile, Song downloadSong)
 {
     using (var tagTemp = TagLib.File.Create(resultFile.Path))
     {
         tagTemp.Tag.Title            = downloadSong.Title;
         tagTemp.Tag.Album            = downloadSong.Album;
         tagTemp.Tag.AlbumArtists     = downloadSong.AlbumArtists;
         tagTemp.Tag.AlbumArtistsSort = downloadSong.AlbumArtistsSort;
         tagTemp.Tag.AlbumSort        = downloadSong.AlbumSort;
         tagTemp.Tag.TitleSort        = downloadSong.TitleSort;
         tagTemp.Tag.Track            = downloadSong.Track;
         tagTemp.Tag.TrackCount       = downloadSong.TrackCount;
         tagTemp.Tag.Disc             = downloadSong.Disc;
         tagTemp.Tag.Composers        = downloadSong.Composers;
         tagTemp.Tag.ComposersSort    = downloadSong.ComposersSort;
         tagTemp.Tag.Conductor        = downloadSong.Conductor;
         tagTemp.Tag.DiscCount        = downloadSong.DiscCount;
         tagTemp.Tag.Copyright        = downloadSong.Copyright;
         tagTemp.Tag.PerformersSort   = downloadSong.Genres;
         tagTemp.Tag.Lyrics           = downloadSong.Lyrics;
         tagTemp.Tag.Performers       = downloadSong.Performers;
         tagTemp.Tag.PerformersSort   = downloadSong.PerformersSort;
         tagTemp.Tag.Year             = downloadSong.Year;
         if (downloadSong.PicturePath != null)
         {
             if (tagTemp.Tag.Pictures != null && tagTemp.Tag.Pictures.Length > 0)
             {
             }
             else
             {
                 using (var referen = await(RandomAccessStreamReference.CreateFromUri(new Uri(downloadSong.PicturePath))).OpenReadAsync())
                 {
                     var p = new List <Picture>
                     {
                         new Picture(ByteVector.FromStream(referen.AsStream()))
                     };
                     tagTemp.Tag.Pictures = p.ToArray();
                 }
             }
         }
         tagTemp.Save();
     }
 }