Montag, 3. Dezember 2012

Windows Phone 8–Usage of Windows.Storage

If you want to implement a file access operation for Windows 8 you have the spoilt of choice: Old style with System.IO.IsolatedStorage or new style with the new WinRT API and classes in the Windows.Storage namespace. The first one will work for Windows Phone 7 and the second one only for Windows Phone 8 but also for a Windows 8 operating system and Metro styled apps.

I tried both solutions and here are the two code fragments which loading a file in a folder and deserialize them to a List of type <T>:

The solution using Isolated Storage:

        public static List<T> LoadList<T>(string folderName, string dataName) where T : class
        {
            var retval = new List<T>();
 
            if (!IsoStore.DirectoryExists(folderName))
            {
                IsoStore.CreateDirectory(folderName);
            }
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            using (var stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
            {
                if (stream.Length > 0)
                {
                    var dcs = new DataContractSerializer(typeof(List<T>));
                    retval = dcs.ReadObject(stream) as List<T>;
                }
            }
            return retval;
        }

And the same with using the new WinRT API and the classes in the Storage namespace:

        public static async Task<List<T>> LoadList<T>(string folderName, string dataName) where T : class
        {
            StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
            if (!await applicationFolder.FolderExistsAsync(folderName))
            {
                applicationFolder.CreateFolderAsync(dataName);
            }
            var retval = new List<T>();
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            if (await applicationFolder.FileExistsAsync( fileStreamName))
            {
 
                IStorageFile storageFile = await applicationFolder.GetFileAsync(fileStreamName);
 
                using (var inStream = await storageFile.OpenSequentialReadAsync())
                {
                    var serializer = new DataContractSerializer(typeof(List<T>));
                    retval = (List<T>)serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            return retval;
        }

Sonntag, 2. Dezember 2012

Windows Phone 8– WorkTime app weekend

Normally this weekend I planned to participate a Duathlon, but because of my current cold I switch the plan and made my own Windows Phone 8 Hackathon weekend (the same as the last one).

Me as designer, programmer and product owner of the nice new app WorkTime. Windows Phone 8 development with all the fun and pains, if you want to implement pattern like MVVM straight forward. Especially this week I fight with a general validation mechanism. I will post some of my approaches to implement a very smart solution at the next days:

Validation code is than looking in the view model constructor like this:

            AddValidationFor(() => CustomerName)
               .When(x => string.IsNullOrEmpty(x._customerName))
               .Show(AppResources.InvalidNotNullOrEmpty);

            AddValidationFor(() => OrderName)
                .When(x => string.IsNullOrEmpty(x._orderName))
                .Show(AppResources.InvalidNotNullOrEmpty);

            AddValidationFor(() => ProjectHoursMax)
              .When(x => x._projectHoursMax<=0)
              .Show(AppResources.InvalidZeroNotAllowed);

            AddValidationFor(() => Start)
            .When(x => x._end <= x._start)
            .Show(AppResources.InvalidStartIsGreaterThanEnd);

Here are some screenshots of the WorkTime app (sorry in German, but English will be also supported. Besides multi language support with sharing Resources among assemblies will be another next post – I need more time :-():

wp_ss_20121202_0016wp_ss_20121202_0007wp_ss_20121202_0008wp_ss_20121202_0009wp_ss_20121202_0010

Samstag, 24. November 2012

Windows Phone 8–ListPicker SelectedItem not bindable

At this week the ListPicker is the second control with issues for binding the SelectedItem property (see http://dotnet-redzone.blogspot.de/2012/11/windows-phone-8longlistselector.html). At this time I tried a second problem solution and made the SelectedIndex my binding property. In my Viewmodel I have to define therefore a method which maps my SelectedIndex to the instance in my list which is populated in the ListPicker (the WorkTasks ObservableCollection):

private int GetWorkTaskIndexFromId(string id)
        {
            for (int index = 0; index < this.WorkTasks.Count; index++)
            {
                if (this.WorkTasks[index].UniqueId == id)
                {
                    return index;
                }
            }

            return 0;
        }

My property for the SelectedIndex in the ViewModel looks like this:

       public int SelectedWorkTaskIndex
        {
            get
            {
                return _selectedWorkTaskIndex;
            }

            set
            {
                _selectedWorkTaskIndex = value;
                if (_allowedToChangeValue && _selectedWorkTaskIndex >= 0)
                {
                    this.SelectedEntry.WorkTask = WorkTasks[value];
                }

                this.RaisePropertyChanged("SelectedWorkTaskIndex");
            }
        }

The last step was to set the SelectedWorkTaskIndex corerctly after loading the instance of my ViewModel connected model. This is done in my implementation of the LoadWorkTask RelayCommand:

        private void LoadWorkTaskList()
        {
            try
            {
                 ....
                
               _allowedToChangeValue = true;

                SetWorkTask();
               
            }
            catch (Exception error)
            {
               .....
            }
        }
        private void SetWorkTask()
        {
            if (SelectedEntry.WorkTask != null)
            {
                SelectedWorkTaskIndex = this.GetWorkTaskIndexFromId(SelectedEntry.WorkTask.UniqueId);
            }
            else
            {
                if (WorkTasks != null && WorkTasks.Count > 0)
                {
                    SelectedWorkTaskIndex = 0;
                }
            }
        }

Windows Phone 8–LongListSelector SelectedItem not bindable

Microsoft has now moved the LongListSelector to the basic phone controls, but the LongListSelector control has still the same issue as it was part of the Windows Phone Toolkit. They have forgotten to declare a DependencyObject for the SelectedItem property so you can not bind the SelectedItem property. Or maybe they want to be compatible with this bug :-)

To resolve this I decided in my current project to define a new class LongListSelector in my project namespace which is derived from the LongListSelector control. Here I can define a dependency property and a LongListSelector_SelectionChanged method to handle the binding. It is is important to declare the property in the new class as New, because we want to override the SelectedItem property in the Microsoft control.

Here is my code to do this:

public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
    {
        public LongListSelector()
        {
            SelectionChanged += LongListSelector_SelectionChanged;
        }

        void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedItem = base.SelectedItem;
        }

        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register(
                "SelectedItem",
                typeof(object),
                typeof(LongListSelector),
                new PropertyMetadata(null, OnSelectedItemChanged)
            );

        private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = (LongListSelector)d;
            selector.SelectedItem = e.NewValue;
        }

        public new object SelectedItem
        {
            get { return GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }
    }

Sonntag, 18. November 2012

Windows Phone 8–Localization of App and tile title

My current WorkTime@WP8 Windows Phone 8 should support different languages. This is a easy task for every .NET developer – Resource files are the correct answer. But what doing with the title of the app and the title of the live tiles? These Ressouces are part of the WMAppManifest.xml file, so we cannot use the normal Resource files.

The answer:

A C++ Dll project with a string table and referring the title with Title="@Sdx.WorkTime.WP8.AppResLib.dll,-100"
in the WMAppManifest.xml

(my first C++ project since 8 years)

To localize the app title, you must create the mentioned resource-only DLL, as well as separate Multilingual User Interface (MUI) files for each display language that your app targets (see screenshot).

image

After I have done this painful steps, it works great!

More details you can find here:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff967550(v=vs.105).aspx

Windows Phone 8–WorkTime project started

This weekend I started with a new Windows Phone project – a time registration app for people who works in projects or have to report their daily work. The Windows phone app will have several data provider (local and Microsoft CRM for the first time). My colleagues at the SDX AG working on an Windows 8 Metro app (C# and XAML), which will be deployed the next weeks. Because the lack of an mobile application to check in project times and to find out what new features (main reason) are in the Windows Phone SDK, I started the WorkTime@WP8 project.

My first goal was to build a clickable prototype and here are the first screenshots:

Windows Phone 8Windows Phone 8 New appWindows Phone 8 SDX WorkTime

With Windows Phone 8 you can make screenshots by pressing the power and windows button at the same time (very nice feature).

Postings about my experience and “lessons learned” during this Windows Phone development will coming time-by-time….

Windows Phone 8–TypeScript crashes WP8 Debugger

TypeScript 0.8.1 is now available and bring us the long desired Source Level Debugging. That means debugging directly the TypeScript​ source files :-)

http://blogs.msdn.com/b/typescript/archive/2012/11/15/announcing-typescript-0-8-1.aspx

Nice feature, BUT!!!!!!! NOT FOR WINDOWS PHONE DEVELOPERS:

I spend today several hours with installing and reinstalling Visual Studio 2012 and the new Windows Phone 8 SDK, because if I attached a debugger to my Windows Phone project the Visual Studio will be crashed. deactivating and reinstalling several extensions for Visual Studio 2012 it was TypeScript which causes the crashes of Visual Studio 2012

Sad smile