Reading WinRT component embedded resource file in windows 8 store javascript app

A WinRT component can used to include some common code along with embedded resources that can be reused in store app irrespective of language in which it is developed like C#, JavaScript etc.
In this article, I’ll explain how to read a WinRT component embedded resource file from JavaScript app. App reads content from embedded resource and replace your page content with new content.

1. Create a WinRT component

1. Create a new windows store apps class library or WinRT component say with name ‘ExampleLib’.
WinRT component

2. If it is a class library, open its properties and change output to WinRT component.

Class library settings

3. Add a text file say ‘Data.txt’ in the project root folder with some text and change to embedded resource from its properties.

Embedded resource

4. Add a new C# code file ResHelper.cs in the project root folder and add the following code in that

using System;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Foundation;

namespace ExampleLib
{
    public  sealed class ResHelper
    {
       static async Task<string> ReadResourceAsync(Assembly assembly, string resource)
        {
            string xml;
            using (var stream = assembly.GetManifestResourceStream(resource))
            {
                    using (var reader = new StreamReader(stream))
                    {
                        xml = await reader.ReadToEndAsync();
                    }
            }
            return xml;
        }
        public static IAsyncOperation GetConfiguration(string fileName)
        {
            return (ReadResourceAsync(typeof(ResHelper).GetTypeInfo().Assembly, fileName)).AsAsyncOperation();
        }

    }
}

}

2. Create a windows store app in javascript

1. Create a new windows store app under language javascript (blank app is fine)
2. Add reference to ExampleLib
3. Open default.js and add the following code in activated.

args.setPromise(WinJS.UI.processAll().then(function () {

//call getConfiguration method with fully qualified
//file name (including dll name, folder path if any and file name)
ExampleLib.ResHelper.getConfiguration("ExampleLib.Data.txt")
.done(function (result) {
document.body.innerText = result;
}, function (err) {
document.body.innerText = err;
});

}));

Complete solution looks like as below

Projects

All done, deploy and run the app, now you’ll see embedded resource content as your main page content. Try with invalid file name; you’ll see an error message

you can download solution from here ExampleApp

Leave a Reply

Your email address will not be published. Required fields are marked *