Skip to content
Archive of posts filed under the Uncategorized category.

INotifyPropertyChanged, WinRT and Shortcuts

INotifyPropertyChanged interface is the key to data binding in many UI Microsoft frameworks, such as Windows Forms, WPF and Silverlight.  All controls in all those frameworks listen to this interface in the classes these controls are bound to and refresh the UI based on those changes.  This interface lives in System.ComponentModel, and you can read more about it here.

In WinRT, Windows 8 runtime this interface moved to a different namespace – Windows.UI.Xaml.Data.  You can see details of here.

As this interface is important, and I want to rely on it in new features I am going to add to my WinRT database project, I wanted to make it easier for people to create classes that implement it and easily add properties to those classes.  So, I wanted to publish this knowledge as well as walk through some of the Visual Studio features that allow  developers create item templates and snippets.  I am planning to use both in this quick post.

Let’s start by creating a class template.  We start by creating a class and make it look like we want it to.  It is really easy, and here is the entire code.

using System;
using Windows.UI.Xaml.Data;

namespace Application1
{
    public class NotifyPropertyChangedClass : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

 

Now, we need to create a class template.  This step is just as easy.  Select Export Template from File menu in Visual Studio:

image

 

Click Next

image

We are selecting our class here, then clicking next.

image

We will skip the references (uncheck all), then click Next.

image

On this last screen I am going to give my new template name and description, I can optionally add icon and preview image, select to automatically import the template, then click Finish.

No, to test this template, I am just right-click on property, select Add New item, then search for notify property changed.

image

Just change the class name and click Add.  Voila – new class that looks just like my template has been added.

Now the snippets.  I am going to use “propfull” snippet as a base.  This snippet adds a property with backing field.  First, I need to see where those snippets are installed.  I can see that by going to Tools –> Code Snippets Manager, then selecting your language, C# in my case.

image

I just expand Visual C# tree node, then I can see the Location.  I am going to that location, find file calld propfull,snippet, then copy it to any folder.  I then rename it propnpc.snippet, where ncp stands for Notify Property Changed.  You can use any name you like.  Then I edit this file in Visual Studio. 

image

I edit Title, description and shortcut, as well as author.  The last part is edit the actual snippet code (in light grey at the bottom of the screenshot).  I simply add the call to OnPropertyChanged method I established when I created a class template before.  Here is the code:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propnpc</Title>
            <Shortcut>propnpc</Shortcut>
            <Description>Code snippet for property and backing field that calls property changed</Description>
            <Author>Sergey Barskiy</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[private $type$ $field$;

    public $type$ $property$
    {
        get { return $field$;}
        set { $field$ = value; OnPropertyChanged("$property$"); }
    }
    $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

The last step is to copy the new snippet back to the original folder.  I could also establish new folder for custom template, but I do not feel like dealing with that.  Now, just type propnpc and hit Tab in your newly added class, and you end up with the following:

image

Just keep changing data, and hitting Tab to advance to the next expansion area, and you will end up with:

image

You are done.  You can also take this a step further, and create a base abstract class that implement INotifyPropertyChanged, then have all your classes inherit for it.

Enjoy.

Thanks.

Post to Twitter

Reading and Writing Files in WinRT

I started converting my Windows Phone database project to WinRT. If you read the description of that project, you see that it is using Isolated Storage. There is no Isolated Storage in WinRT, so I had to practically re-write the entire project, at least all parts that deal with persistence. I have a preview now available, but since there is no TFS integration yet in Visual Studio 11 Express preview, I am not quite ready to post the project to CodePlex yet, but I wanted to post it on my blog as early preview.

As part of writing the file access login, I wrote a couple of extension methods for StorageFile class, those that used to exist in .NET. Primarily, I am referring to WriteAllText and ReadAllText methods. It took a bit to figure those out, and I wanted to post my research here for other folks’ benefits.

Let’s take a look at the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

namespace WinRTDatabase.IO
{
    /// <summary>
    /// Storage File extensions for reading and writing
    /// </summary>
    public static class StorageFileExtensions
    {
        /// <summary>
        /// Asynchronously write a string to a file
        /// </summary>
        /// <param name="storageFile">StorageFile to write text to</param>
        /// <param name="content">Text to write</param>
        /// <returns>Task/ void if used with await</returns>
        async public static Task WriteAllTextAsync(this StorageFile storageFile, string content)
        {
            var inputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);
            var writeStream = inputStream.GetOutputStreamAt(0);
            DataWriter writer = new DataWriter(writeStream);
            writer.WriteString(content);
            await writer.StoreAsync();
            await writeStream.FlushAsync();
        }

        /// <summary>
        /// Asynchronously read a string from a file
        /// </summary>
        /// <param name="storageFile">StorageFile to read text from</param>
        /// <returns>Task/ void if used with await</returns>
        async public static Task<string> ReadAllTextAsync(this StorageFile storageFile)
        {
            string content;
            var inputStream = await storageFile.OpenAsync(FileAccessMode.Read);
            var readStream = inputStream.GetInputStreamAt(0);
            var reader = new DataReader(readStream);
            uint fileLength = await reader.LoadAsync((uint)inputStream.Size);
            content = reader.ReadString(fileLength);
            return content;
        }
    }
}

No color coding yet in VS 2011, sorry for black and white code.  As you can see right away, all file IO must be asynchronous in WinRT at some point.  In both methods I am getting a stream from the file, then creating either input or output stream, then using either DataReader or DataWriter I am getting or setting the content of the file.me

Another interesting aspect is that both methods are asynchronous, but using different return values.  Return value of Task will translate into void method when used with async keyword.  Return value of Task<string> will translate into just string when using with async keyword.

await file.WriteAllTextAsync(content);

or

string content = await file.ReadAllTextAsync();

Stay tuned to sample WinRT application that is using my WinRT database that is based on file system.

Post to Twitter

Impressions From Build Conference

Today was the first day of the Build Conference in Anaheim.
I wanted to type my notes before going to bed.
First of all, I am typing this blog post on my brand new Windows 8 tablet. No MS Word on it, so forgive all the typos.
The day started with key note. You can watch it on www.buildwindows.com
I thought all the demos were quite impressive. Windows 8 is totally following the footsteps or windows phone 7, fully embracing Metro design principles. Not really a surprise that I liked that a lot, since I really like my windows phone. A variety of devices were on the stage, stressing the fact that windows 8 will run on all of them, including tablets. The same coded base on all them, The same apps will run on all the devices then, right?
Coding experience included C++, C#, VB.NET, JavaScript/HTML, XAML. No, not Silverlight, just XAML. Seems very similar to Silverlight to me. All of these approaches rely on new runtime, WinRT. All the apps use this new run time to utilize features in Windows 8. Unlike .NET, this run time is part of Windows, optimized for performance. Visual studio is the tool that will be used to build applications that use this run time. It comes with a number of project templates that make it easy to write applications that fit naturally into Metro style. This includes look and feel, but also animations and styles.
I am not quite clear what happens to .NET in this brave new world.
We will just have to wait and see.

Post to Twitter