Quantcast
Channel: Building Windows Store apps with C# or VB (archived) forum
Viewing all 7782 articles
Browse latest View live

RenderTargetBitmap.RenderAsync() & Popup : Value does not fall within the expected range

$
0
0

Hi, I am using RenderTargetBitmap to capture a snapshot of aPage following the instruction of a msdn sample. My problem is: if I put the page on aPopup Control, then RenderTargetBitmap.RenderAsync() would throw ArgumentException(Additional information: "Value does not fall within the expected range"), but if I justNavigate to the page using Frame.Navigate() method, everything would be fine. What's wrong with Popup Control? Below is the code:

BlankPage1.xaml

<Page x:Class="Test.BlankPage1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:Test"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
          Width="600"
          Height="600"><Button Content="save image"
                Click="Button_Click"
                HorizontalAlignment="Center"
                VerticalAlignment="Center" /></Grid></Page>

BlankPage1.xaml.cs

namespace Test { public sealed partial class BlankPage1 : Page { public BlankPage1() { this.InitializeComponent(); } public async Task CaptureElementToBitmapAsync(FrameworkElement element, string suggestedFileName) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(element); //throw ArgumentException

IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedFileName = suggestedFileName; savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.DefaultFileExtension = ".png"; savePicker.FileTypeChoices.Add("png Image", new string[] { ".png" }); StorageFile file = await savePicker.PickSaveFileAsync(); if (file == null) { return; } using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } } private async void Button_Click(object sender, RoutedEventArgs e) { await CaptureElementToBitmapAsync(this, "test"); } } }


Main.xaml.cs

namespace Test { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) {

//method 1: not work BlankPage1 page = new BlankPage1(); Popup popup = new Popup(); popup.Child = page; popup.IsLightDismissEnabled = true; popup.IsOpen = true; //method 2: this would work //this.Frame.Navigate(typeof(BlankPage1)); } } }




not able to play url in web view wp8

$
0
0

hi I have a url which is playing in desktop IE Web Browser but not playing in wp8 web browser

here is my url

http://54.179.170.143/multitvfinal/index.php/details?id=37&type=live&device=ios

Error loading player, no Playable source found wp8

$
0
0

hi I have a url  http://54.179.170.143/multitvfinal/index.php/details?id=37&type=live&device=ios

when I Navigate this url in to my Wp8 webBrowser then it is giving me error 

ths error is 

Error loading Player no Playable source found.

my code is wb.Navigate(new uri("http://54.179.170.143/multitvfinal/index.php/details?id=37&type=live&device=ios",UriKind.Absolute);

Font is not displayed properly in Windows Phone

$
0
0

Hello I am trying to make a Book App for Windows Phone. There are words that are in Simsun ExtB font. These words appear fine in my Windows desktop, but not appearing properly in my Windows Phone. I have installed the latest Traditional Chinese and Simplified Chinese packages from Windows Phone 8.1 already.  I used Internet Explorer in my Windows Phone to search in Unicode.org, and the word appears as a "square". Please look at the link below (the column where it said "your browser"....MS doesn't allow me to post pictures). I am not a tech person...what is the way to solve this problem? &nbsp;I am using Windows studio app to build the app....I have downloaded Viusal Basic express as well. If anyone can point me to the right direction, I am highly appreciated it. Thanks!!!

http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=24656

how to save contents of two different rich edit box into single rtf file in windows 8.1 app

$
0
0
Developer, I have requirement to save registration data into rtf file.. These can only be done by if I put rich edit box to fill the data.. Now if I am going to write the code for saving the data of different rich edit box into one particular file, it only saves the data of last rich edit box.. So plzz suggest that how can I save the contents of different rich edit box together into one rtf file.

Memory Leak using InvokeScriptAsync for WebView

$
0
0

I'm updating Webview content frequently using InvokeScriptAsync method.  With each call memory keeps going up and never goes back down.  Since I'm sending large data and quite often the app can reach above 1.5Gb in memory within few minutes.  Is there anyway to force Garbage Collect on webview manually?

My code:

webView.Navigate(new Uri("ms-appx-web:///html/main.html")) 

private async void createMemoryLeak(string execute, JsonObject json){

var memoryLeak = await webView.InvokeScriptAsync("eval", new string[] { "\"something that does nothing to DOM, but has really long string to cause memory leak faster. With every click memory keeps going up.\"" });

}

This is deal breaker, so any help will be appreciated.

Thanks

country code returned by geolocator class varies from PC to PC, but all PCs are at same location.

$
0
0

Hi Everyone,

we are developing one location based app for win8 and wp8. to get the location (only country code) ,we are using geolocator class as shown below. but, the problem here is the country codes returned by geolocator are varying from pc to pc, though all pcs are at one location.

this leads to the major problems in our application.

how geolocator class gets the location of our pc? what is the root cause for this problem?

can anybody please help me to figure out this issue?

 Geolocator geo = new Geolocator();
                            CancellationTokenSource cts = new CancellationTokenSource();
                            CancellationToken token = cts.Token;
                            Geoposition pos = await geo.GetGeopositionAsync();
                            countrycode= pos.CivicAddress.Country.ToString().ToLower()



Using FlipView to create a PhotoViewer with pinch to zoom capability (like WP8 PhotoApp)

$
0
0

Hello,

I'm currently developing a Universial App using WinRT to develop for Windows 8.1 and WP8.1. Inside that app I want to view a couple of images. Viewing the images works just fine with a FlipView but the disadvantage is, you cannot zoom. I searched for a solution for several hours but I cannot manage to find something good.

Most solutions say I should use a ScrollViewer but it seems that it cannot work fine with the flipView as I'm still able to switch the image while I have a zoomed image and thus the next image is also zoomed as well.

The best solution I could manage to find is the MediaViewer Control but unfortunately it's written for WP8 Silverlight so I cannot use it directly. I tried to port it to WinRT but I failed because it's using a ViewportControl and there's no such control for WinRT, we only have a ViewBox but I don't know if it behaves like the ViewportControl and it's also lacking some methods which are used by the MediaViewer Control.

Can someone help me building a control which supports zooming and switching images? My goal is to reach a similar behaviour as in the photo app for WP8, that means I'm completely able to switch images as long as the aren't zoomed. If the ZoomLevel is > 1, then it should only be possible to pan the image but not trigger any item switch.

Any help is greatly appreciated

Regards


Hub Page item limit.

$
0
0
In my hub app, I've got a tile section to show all my locations from my sampledata.json. But I do not want all of the data to show at once

Auto Size Textbox with text font change VS2013 in VB.net

$
0
0

Hi all,

I use Visual Studio2013 to write on a store app in VB.net and I try to set a textbox height and width to auto and after a font change read the new height and width as double values.

Thank you for your help

Playing Encrypted Video File with MediaElement

$
0
0

My Windows Store app has an encryption / decryption option that lets people store all their data files (which include images and movies) encrypted in their project folder for potential copying over the Internet, to cloud services, etc. (Trust me, this is necessary, and no, BitLocker, SSL, etc. are insufficient).

To play videos, the app uses MediaElement. I'd like to be able to set the MediaElement source to a stream that decrypts the file on demand. With desktop apps, I would just use a CryptoStream, but Windows Store apps don't appear to support CryptoStream. 

Can anyone suggest an efficient way to do this?

Other options that come to mind (each with significant disadvantages)-

- Decrypt the whole file to a temporary location, then source MediaElement with the temp file - obviously bad if the app or device crashes before the temp file is deleted though, and not particularly efficient.

- Create a custom media stream source that decrypts the data frame by frame, sample by sample, and feeds it to the MediaElement; problem with this is that my encryption function would likewise have to scramble the video and audio data sample by sample, rather than encrypt the whole file once, meaning lots of C++/DirectX nastiness or dealing with media transcoding which I've not had good experiences with (maybe they've fixed it, but earlier this year I found the whole transcoding system to be riddled with memory leak problems and wound up having to write everything in C++ with DirectX)

- Write a custom CrytpoStream that implements IRandomAccessStream? I honestly wouldn't know where to begin though.

Any other ideas appreciated. Thanks!

Peter

Windows Class Library in MVVM : access ReadOnly properties from ViewModel. Use Behaviors ?

$
0
0

Hello, 

i'm currently developping a Windows Class Library in c# / Xaml. This library will be integrated to an windows 8 ModernUI app. I use MVVM design pattern, and XAML files are embedded ressources in the library. I load those XAML resources at runtime using XamlReader. 

var xamlPageStream =typeof(EntryPoint).GetTypeInfo().Assembly.GetManifestResourceStream(nameInPackage);var sr =newStreamReader(xamlPageStream);var xamlPage = sr.ReadToEnd();returnXamlReader.Load(xamlPage)asFrameworkElement;

I need to read / access, from viewModel, to ReadOnly properties of xaml component, declared in my pages. For example, i need to read ActualHeight / ActualWidht of a canvas element, in my viewmodel.  
Thoses properties are not bindable to a viewmodel property, because they are ReadOnly. 

My first question : do you know a way to access those properties (only for reading purposes) from viewmodel ? 

My investigations was unsuccessful for the moment, but i read something about using a behavior, added to canvas compopent, in order to get and send the looked for property to viewmodel, at each change of this property. 

I tried to create a customized behavior, and to reference it on my Canvas Control. 

I added Behavior SDK in my VS projects (Class Library and caller program). I referenced it in my XAML page. Here is an extract from code : 

<Page ...xmlns:Interactivity="clr-namespace:Microsoft.Xaml.Interactivity;assembly=Microsoft.Xaml.Interactivity" ...>

[...]

<ContentControl ...><Interactivity:Interaction.Behaviors></Interactivity:Interaction.Behaviors></ContentControl>

 

The content assist of VS works fine with this code, and the compilation is ok. Unfortunately, at runtime, when XamlReader reads the XAML, i get an ParseException : 

ParseException : The attachable property 'Behaviors' was not found in type 'Interaction'.

Did i forget something ? Or did i misunderstood something ? Why does the XamlReader fail to find Behavior, whereas content assist and compilation success ? 

Is there an other way to proceed ?  

Thank you by advance for your answers. 

Lumia Imaging SDK System Argument Exception value does not fall within expected range

$
0
0

I am trying to use the Lumia Imaging SDK 2.0 to set greyscale on an image. I have achieved this ok with the code below with images encodes as JPEG but if I load an image encoded as ARW (Sony RAW) the image displays ok but when I try to run the code for greyscale it crashes with the Argument Exception value does not fall within expected range. Whilst debugging I cannot see any difference with the writable bitmap.

Code to load the image which works ok for JPEG and ARW

                if (sourceFile != null)
                {
                    byte[] srcPixels;
                    RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromFile(sourceFile);
                    using (IRandomAccessStreamWithContentType filestream = await streamRef.OpenReadAsync())
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(filestream);
                        BitmapFrame frame = await decoder.GetFrameAsync(0);
                        PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
                        srcPixels = pixelProvider.DetachPixelData();
                        wid = (int)frame.PixelWidth;
                        hgt = (int)frame.PixelHeight;
                        writableBitmap = new WriteableBitmap(wid, hgt);
                        Stream pixelStream = writableBitmap.PixelBuffer.AsStream();
                        pixelStream.Seek(0, SeekOrigin.Begin);
                        pixelStream.Write(srcPixels, 0, (int)srcPixels.Length);
                        source = new StorageFileImageSource(sourceFile);
                        effect = new FilterEffect(source);
                        writableBitmapRenderer = new WriteableBitmapRenderer(source);
                        canvasMain.Width = wid;
                        canvasMain.Height = hgt;
                        filestream.Seek(0);
                        target.Source = writableBitmap;
                    }
                }

Code for the greyscale filter:

                    filterlist.Add(new Lumia.Imaging.Adjustments.GrayscaleFilter());
                    effect.Filters = filterlist;
                    writableBitmapRenderer = new WriteableBitmapRenderer(effect, writableBitmap);
                    await writableBitmapRenderer.RenderAsync();
                    isRendering = false;
                    CanUndo = true;
                    buttonUndo.IsEnabled = true;
                    writableBitmap.Invalidate();


Mal

How to I apply snapview hubsection

Can I Parse json Using Key vale in windows phone 8

$
0
0

hi.

I have a json structure and the json changes dynamically

so can I parse the json using key value pair like in android or ios


0x8001010E (RPC_E_WRONG_THREAD)

$
0
0

Hello,

I am getting this error from Visual Studio:

 "0x8001010E (RPC_E_WRONG_THREAD)"

It occurs when from a roaming data changed Event the "DefconStatus" Property is going to be changed while the app is running. I guess it could be handled by the Dispatcher or async await stuff. The Change of the UI by the roaming Event is of course some Kind of an Invokation of the normal way the data changes. I would be grateful for any ideas or Solutions.

The app itself is located here: MyDEFCON

//Event Subscription in the ViewModel constructor
public MainPageViewModel(INavigationService navigationService)
        {
            Windows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged;
            _navigationService = navigationService;
        }

//The causing property
string _DefconStatus = default(string);
        public string DefconStatus { get { return _DefconStatus; } set { SetProperty(ref _DefconStatus, value); } }

//Eventhandler
void Current_DataChanged(ApplicationData sender, object args)
        {
            LoadDefconStatus();
        }

//The load from roaming Settings method
private void LoadDefconStatus()
        {
            Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
            if (roamingSettings.Values.ContainsKey("defconStatus"))
            {
                roamingUpdate = true;
                SetDefconStatus(Convert.ToInt16(roamingSettings.Values["defconStatus"].ToString()));
            }
            else SetDefcon5();
        }
//Status setter called from roaming update
private void SetDefconStatus(int status)
        {
            switch (status)
            {
                case 1:
                    SetDefcon1();
                    break;
                case 2:
                    SetDefcon2();
                    break;
                case 3:
                    SetDefcon3();
                    break;
                case 4:
                    SetDefcon4();
                    break;
                case 5:
                    SetDefcon5();
                    break;
                default:
                    break;
            }
        }

//One of the five DEFCON setter
private void SetDefcon1()
        {
            DefconStatus = "1";
            defconSet = true;
            Defcon1 = true;
            Defcon2 = false;
            Defcon3 = false;
            Defcon4 = false;
            Defcon5 = false;
            UpdateTileToDefcon1();
            if (!roamingUpdate)
            {
                SaveDefconStatus();
            }
            roamingUpdate = false;
            defconSet = false;
        }

WinRT Background Task with Time Trigger Error

$
0
0

I have defined my Background Task as follows:

publicsealedclassBackgroundSynchronization:IBackgroundTask{public async voidRun(IBackgroundTaskInstance taskInstance){BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();//code//Network Calls//Updating Local DB (SQLite)

            myRepository.Save(entity);// Saves entity in SQLite Table, and Entity has a  Current DateTime field too.

            deferral.Complete();}}

And Task Register class as

publicstaticclassBackgroundTaskRegister{publicstaticBackgroundTaskRegistrationRegisterBackgroundTask(string taskEntryPoint,string taskName,IBackgroundTrigger trigger,IBackgroundCondition condition){foreach(var cur inBackgroundTaskRegistration.AllTasks){if(cur.Value.Name== taskName){return(BackgroundTaskRegistration)(cur.Value);}}var builder =newBackgroundTaskBuilder();

        builder.Name= taskName;
        builder.TaskEntryPoint= taskEntryPoint;
        builder.SetTrigger(trigger);if(condition !=null){
            builder.AddCondition(condition);}BackgroundTaskRegistration task = builder.Register();return task;}}

And I have registered the triiger in my app as

TimeTrigger myTrigger =newTimeTrigger(15,false);
    await BackgroundExecutionManager.RequestAccessAsync();string entryPoint ="BackgroundTask.BackgroundSynchronization";string taskName ="Example per 15 minute background task";BackgroundTaskRegistration tsk =BackgroundTaskRegister.RegisterBackgroundTask(entryPoint, taskName, myTrigger,null);

    tsk.Completed+=newBackgroundTaskCompletedEventHandler(OnCompleted);

I also have OnComplete method in my App

private async voidOnCompleted(IBackgroundTaskRegistration task,BackgroundTaskCompletedEventArgs args){var settings =ApplicationData.Current.LocalSettings;var message = settings.Values["backgroundSyncStatus"].ToString();var folder =ApplicationData.Current.LocalFolder;StorageFile file;var x = await File.DoesFileExistInLocalAsync("BackgroundTaskSucceedLog.txt");if(!x)
                file = await folder.CreateFileAsync("BackgroundTaskSucceedLog.txt");else
               file = await ApplicationData.Current.LocalFolder.GetFileAsync("BackgroundTaskSucceedLog.txt");

            await Windows.Storage.FileIO.AppendTextAsync(file, message.ToString()+" "+DateTime.Now.ToString()+Environment.NewLine);}

The background tasks triggers successfully, & the data is saved to SQLite DBmyRepository.Save(entity); table only for the first run. I came to this conclusion as I had logged the entries inOnComplete method.

The logger results confused me more

Logger results

2/16/201510:51:41 PM     <--DataSavedinSQLiteforthis entry2/16/201511:07:03 PM2/16/201511:22:26 PM2/16/201511:37:39 PM2/16/201511:52:51 PM2/17/20155:33:00 AM       <--DataSavedinSQLiteforthis entry

The data in SQLite is saved only for the first Background Task "for a day". I tried to Debug Background Task., For first run, Everything runs smoothly, & for subsequent run, the compiler after reachingmyRepository.Save(entity);, jumps directly to OnComplete method. WHY.???

Semantic Zoom - Show letters containing no items

$
0
0

How can I show letters of the alphabet, which contain no items beginning with that letter (in gray) within the ZoomedOutView view of my semantic zoom control?

I want to achieve something like this (excluding 'Social', 'Favorites' and '#'): 

but I end up with this:

MetropolitanDataSource.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EELL
{
    using System;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Media;

    // To significantly reduce the sample data footprint in your production application, you can set
    // the DISABLE_SAMPLE_DATA conditional compilation constant and disable sample data at runtime.
#if DISABLE_SAMPLE_DATA
    internal class SampleDataSource { }
#else

    public class Item : System.ComponentModel.INotifyPropertyChanged
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        private string _Station = string.Empty;
        public string Station
        {
            get
            {
                return this._Station;
            }

            set
            {
                if (this._Station != value)
                {
                    this._Station = value;
                    this.OnPropertyChanged("Station");
                }
            }
        }

        private string _Zone = string.Empty;
        public string Zone
        {
            get
            {
                return this._Zone;
            }

            set
            {
                if (this._Zone != value)
                {
                    this._Zone = value;
                    this.OnPropertyChanged("Zone");
                }
            }
        }

        private string _Link = string.Empty;
        public string Link
        {
            get
            {
                return this._Link;
            }

            set
            {
                if (this._Link != value)
                {
                    this._Link = value;
                    this.OnPropertyChanged("Link");
                }
            }
        }
    }

    public class GroupInfoList<T> : List<object>
    {

        public object Key { get; set; }


        public new IEnumerator<object> GetEnumerator()
        {
            return (System.Collections.Generic.IEnumerator<object>)base.GetEnumerator();
        }
    }


    public class StoreData
    {
        public StoreData()
        {
            Item item;

            item = new Item();
            item.Station = "Aldgate";
            item.Link = "/Lines and Stations/Metropolitan/Aldgate_(Metropolitan).xaml";
            Collection.Add(item);


            item = new Item();
            item.Station = "Moorgate";
            item.Link = "/Lines and Stations/Metropolitan/MOG_(Metropolitan).xaml";
            Collection.Add(item);
        }



        private ItemCollection _Collection = new ItemCollection();

        public ItemCollection Collection
        {
            get
            {
                return this._Collection;
            }
        }

        internal List<GroupInfoList<object>> GetGroupsByCategory()
        {
            List<GroupInfoList<object>> groups = new List<GroupInfoList<object>>();

            var query = from item in Collection
                        orderby ((Item)item).Zone
                        group item by ((Item)item).Zone into g
                        select new { GroupName = g.Key, Items = g };
            foreach (var g in query)
            {
                GroupInfoList<object> info = new GroupInfoList<object>();
                info.Key = g.GroupName;
                foreach (var item in g.Items)
                {
                    info.Add(item);
                }
                groups.Add(info);
            }

            return groups;
        }

        internal List<GroupInfoList<object>> GetGroupsByLetter()
        {
            List<GroupInfoList<object>> groups = new List<GroupInfoList<object>>();

            var query = from item in Collection
                        orderby ((Item)item).Station
                        group item by ((Item)item).Station[0] into g
                        select new { GroupName = g.Key, Items = g };
            foreach (var g in query)
            {
                GroupInfoList<object> info = new GroupInfoList<object>();
                info.Key = g.GroupName;
                foreach (var item in g.Items)
                {
                    info.Add(item);
                }
                groups.Add(info);
            }

            return groups;

        }
    }

    // Workaround: data binding works best with an enumeration of objects that does not implement IList
    public class ItemCollection : IEnumerable<Object>
    {
        private System.Collections.ObjectModel.ObservableCollection<Item> itemCollection = new System.Collections.ObjectModel.ObservableCollection<Item>();

        public IEnumerator<Object> GetEnumerator()
        {
            return itemCollection.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(Item item)
        {
            itemCollection.Add(item);
        }
    }
#endif
}

Metropolitan_line.xaml.cs

using Exits_Expert_London_Lite.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Exits_Expert_London_Lite.Lines_and_Stations.Metropolitan
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Metropolitan_line : Page
    {
        public Metropolitan_line()
        {
            this.InitializeComponent();

            StoreData _storeData = null;

            // creates a new instance of the sample data
            _storeData = new StoreData();

            // sets the list of categories to the groups from the sample data
            List<GroupInfoList<object>> dataLetter = _storeData.GetGroupsByLetter();
            // sets the CollectionViewSource in the XAML page resources to the data groups
            cvs2.Source = dataLetter;
            // sets the items source for the zoomed out view to the group data as well
            (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = cvs2.View.CollectionGroups;
        }

        #region Data Visualization
        /// <summary>
        /// We will visualize the data item in asynchronously in multiple phases for improved panning user experience
        /// of large lists.  In this sample scneario, we will visualize different parts of the data item
        /// in the following order:
        ///
        ///     1) Placeholders (visualized synchronously - Phase 0)
        ///     2) Tilte (visualized asynchronously - Phase 1)
        ///     3) Image (visualized asynchronously - Phase 2)
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void ItemsGridView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            ItemViewer iv = args.ItemContainer.ContentTemplateRoot as ItemViewer;

            if (args.InRecycleQueue == true)
            {
                iv.ClearData();
            }
            else if (args.Phase == 0)
            {
                iv.ShowPlaceholder(args.Item as Item);

                // Register for async callback to visualize Title asynchronously
                args.RegisterUpdateCallback(ContainerContentChangingDelegate);
            }
            else if (args.Phase == 1)
            {
                iv.ShowStation();
                args.RegisterUpdateCallback(ContainerContentChangingDelegate);
            }
            else if (args.Phase == 2)
            {
                iv.ShowZone();
            }


            // For imporved performance, set Handled to true since app is visualizing the data item
            args.Handled = true;
        }

        /// <summary>
        /// Managing delegate creation to ensure we instantiate a single instance for
        /// optimal performance.
        /// </summary>
        private TypedEventHandler<ListViewBase, ContainerContentChangingEventArgs> ContainerContentChangingDelegate
        {
            get
            {
                if (_delegate == null)
                {
                    _delegate = new TypedEventHandler<ListViewBase, ContainerContentChangingEventArgs>(ItemsGridView_ContainerContentChanging);
                }
                return _delegate;
            }
        }
        private TypedEventHandler<ListViewBase, ContainerContentChangingEventArgs> _delegate;

        #endregion //Data Visualization

    }
}

Most Efficent way to List Artitst and Songs

$
0
0

I am working on an application that retrieves available song files from available media servers. The media server I am testing with is a NetGear Router with a USB drive connected.

GetMediaServers(

KnownFolders.MediaServerDevices);

Finds the sever no problem. There are about 300 artists on this server. Also I have the same collection available on a HomeGroup share.

//IReadOnlyList<StorageFolder> artists = await artistFolder.GetFoldersAsync(CommonFolderQuery.DefaultQuery, 10, 10);


           

//QueryOptions qo = new QueryOptions();


           

//qo.IndexerOption = IndexerOption.UseIndexerWhenAvailable;


           

//qo.FolderDepth = FolderDepth.Shallow;


           

//qo.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.ItemName" });


           

DateTimestartTime =DateTime.Now;

           

//StorageFolderQueryResult results = artistFolder.CreateFolderQueryWithOptions(qo);


           

//IReadOnlyList<StorageFolder> artists = await results.GetFoldersAsync(0, 10);


           

IReadOnlyList<StorageFolder> artists = awaitartistFolder.GetFoldersAsync(CommonFolderQuery.DefaultQuery, 0, 10);

            lstMedia.DisplayMemberPath =

"DisplayName";

           

inti = 1;

           

foreach(StorageFolderfolderinartists)

            {

               

Debug.WriteLine(string.Format("{0} - Folder: {1}", i, folder.DisplayName));

                lstMedia.Items.Add(folder);

                i++;

            }

           

DateTimeendTime =DateTime.Now;

           

TimeSpants = (endTime - startTime);

           

Debug.WriteLine(string.Format("Hr {0} Min {1} Sec {2} Ms {3}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds));

I am using the above code to retrieve the lists of artists from the Artists Folder. This is way too slow. From the NetGear server this takes about 30 seconds. From the HomeGroup it takes 2min 8 sec. Why is this so slow? If I use mediaplayer it retrieves these lists instantly.

Is there another approach I should be using?

Thanks for your help!

virtualizing an observable collection for gridview

$
0
0

How can i virtualize my gridview binded by an observable collection using C#

i am using metro Grid Application template which is bounded a sample datasource which uses

ObservableCollection<TvShowsDataGroup> ItemGroups

where i can have 1000 items to add in Group.

so Then after i can call 20 items to be displayed and so on increase on request.

using IVirtualizingVector and placeholder property.

i studied cocoon example but didn't help for my case.

Thanks ,

Abhishek


Abhishek. Senior S/W Consultant

Viewing all 7782 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>