Sonntag, 16. Dezember 2012

Windows Phone 8: Nuget Windows Phone Toolkit language issues

In my current project I want to support English (en-US (default)) and German (de) for all German speaking countries like Austria, Switzerland, Germany. Therefore my supported language setting in my project properties looks like this:

WindowsPhoneLanguages

If you install the Windows Phone Toolkit via Nuget (https://nuget.org/packages/WPtoolkit) there are two issues which you have to resolve.

First: Nuget does not install the language specific satellite assemblies

Second: The Windows Phone Toolkit does not support the basic culture “de”. Only the country specific “de-DE” culture.

To solve this issues, I have downloaded the Windows Phone Toolkit project from Codeplex (http://phone.codeplex.com/) and duplicated the resource file “de-DE” also as “de” in the Windows Phone Toolkit project. After a compilation of the project I copied the resource assemblies to my Nuget package folder:

WindowsPhoneToolkitLanguages

After this I will have the desired support from the Windows Phone Toolkit for the basic culture “de”.

Mittwoch, 5. Dezember 2012

Microsoft Roadshow–Windows 8 Professional

The Professional Touch” - Entwicklung moderner Line-Of-Business Apps!

„Touch-Bedienung, Mobilität, Ergonomie, Design und Produktivität – Nutzer und Kunden erwarten heute von modernen Business-Applikationen die gleichen Qualitäten, die bei Consumer-Anwendungen mittlerweile Standard sind. Darin liegt die Chance, mit modernen Business-Apps Kunden und Mitarbeiter zu begeistern – wenn es gelingt, die neuen Möglichkeiten zu nutzen und gleichzeitig die speziellen Anforderungen der Unternehmens-IT zu erfüllen. Zudem müssen sich Entwicklungsteams in Unternehmen neuen Herausforderungen stellen.

Mit der „SDX Privatbilanz“ bietet die SDX AG einen Showcase, der zeigt, wie die besonderen Merkmale von Windows 8-Apps für attraktive Enterprise Business-Apps genutzt werden können.
An einem Nachmittag geben wir einen kompakten Einstieg in die Thematik.
Informieren Sie sich über die wichtigsten Konzepte, Technologien und Tools und erfahren Sie, wie Sie und Ihr Team in die Entwicklung moderner Business-Apps einsteigen können.


Nur noch eine Plätze frei, also melden Sie sich jetzt an.

Zielgruppe:
Entwickler, technische Entscheider und Entwicklungsleiter

Kosten: €49, inklusive Kaffee und Abendessen

Dienstag, 4. Dezember 2012

Windows Phone 8–Parallel async access fixed

Yesterday I have changed my file IO operations from IsolatedStorage (Windows Phone 7) to Windows.Storage classes (WinRT API for Windows Phone 8). One problem with the asynchronous call is that there could now be parallel calls to the same resource (in this case a file). With async methods you cannot use the common lock mechanism :-(

But my colleague Matthias (@JauMatt) has already found in the web a very nice solution for that: http://qedcode.com/content/awaitable-critical-section

My new code which using the class AwaitableCriticalSection looks than like this and works properly for Windows Phone 8, too:

        public static async Task SaveList<T>(string folderName, string dataName, List<T> dataList) where T : class
        {
            StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
            if (!await applicationFolder.FolderExistsAsync(folderName))
            {
                applicationFolder.CreateFolderAsync(dataName);
            }
 
            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
 
            using (var section = await CriticalSection.EnterAsync())
            {
 
                StorageFile file =
                    await
                    applicationFolder.CreateFileAsync(fileStreamName, CreationCollisionOption.ReplaceExisting);
                using (IRandomAccessStream randomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = randomAccessStream.GetOutputStreamAt(0))
                    {
                        var serializer = new DataContractSerializer(typeof (List<T>));
                        serializer.WriteObject(outStream.AsStreamForWrite(), dataList);
                        await outStream.FlushAsync();
                    }
                }
            }
        }

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); }
        }
    }