본문 바로가기
개발언어/Windows 8 app

ObjectStorageHelper<T> now available for Windows 8 RTM (Windows 8 Xml Utility)

by 엔돌슨 2012. 10. 12.
반응형
ObjectStorageHelper<T> now available for Windows 8 RTM (Windows 8 Xml Utility)

How to Windows8 App Xml Read. 윈도우8 어플에서 xml를 읽어와야 한는 데 괜찮은 유틸클래스가 있다. 하지만 아쉽게 "windows 8 consumer" 버전에서 만든 소스이다. 

하지만 RTM에서도 정상적으로 돌아간다.

원래대로라면 DataContractSerializer 를 이용해서 serializer 해서 저장하여야 한다.

UserDetail Stats = new UserDetail();

                Stats.Id = 1005;

                Stats.Name = "name5";


                StorageFile userdetailsfile = await roamingFolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))

                {

                    // Serialize the Session State.

                    DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetail));

                    serializer.WriteObject(outStream.AsStreamForWrite(), Stats);

                    await outStream.FlushAsync();

                }

 


아래의 소스의 저장 부분을 수정해서 사용해라!~!!!

http://social.msdn.microsoft.com/Forums/is/winappswithcsharp/thread/3a2dddab-03fc-449a-a1e5-fbec6f40c10d 

public async Task<T> SaveASync(T Obj, string FileName)
            {

                FileName = FileName + ".xml";
                try
                {
                    if (Obj != null)
                    {
                        StorageFile file = null;
                        StorageFolder folder = GetFolder(storageType);
                        file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                        using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
                            {
                                serializer.Serialize(outStream, Obj);
                            }
                        }
                    }
                    return default(T);
                }
                catch (FileNotFoundException)
                {
                    //file not existing is perfectly valid so simply return the default 
                    return default(T);
                }
                catch (Exception)
                {
                    throw;
                }
            }

ObjectStorageHelper<T> now available for Windows 8 RTM (Windows 8 Xml Utility) Source!

Download
 

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Xml.Serialization;

using Windows.Storage;

using Windows.Storage.Streams;


namespace QuickTodoListTable.Data.Util

{

    public class StorageHelper

    {

        public enum StorageType

        {

            Roaming, Local, Temporary

        }


        public class ObjectStorageHelper<T>

        {

            private ApplicationData appData = Windows.Storage.ApplicationData.Current;

            public XmlSerializer serializer;

            private StorageType storageType;


            //http://support.microsoft.com/kb/330592/ko

            public ObjectStorageHelper(XmlSerializer serializer)

            {

                this.serializer = serializer;

            }


            public ObjectStorageHelper(StorageType StorageType)

            {

                serializer = new XmlSerializer(typeof(T));

                storageType = StorageType;

            }


            public async void DeleteASync(string FileName)

            {

                FileName = FileName + ".xml";

                try

                {

                    StorageFolder folder = GetFolder(storageType);


                    var file = await GetFileIfExistsAsync(folder, FileName);

                    if (file != null)

                    {

                        await file.DeleteAsync(StorageDeleteOption.PermanentDelete);

                    }

                }

                catch (Exception)

                {

                    throw;

                }

            }


            public async void SaveASync(T Obj, string FileName)

            {


                FileName = FileName + ".xml";

                try

                {

                    if (Obj != null)

                    {

                        StorageFile file = null;

                        StorageFolder folder = GetFolder(storageType);

                        file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);


                        IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                        Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;

                        serializer.Serialize(outStream, Obj);

                    }

                }

                catch (Exception)

                {

                    throw;

                }

            }

            public async Task<T> LoadASync(string FileName)

            {

                FileName = FileName + ".xml";

                try

                {

                    StorageFile file = null;

                    StorageFolder folder = GetFolder(storageType);

                    file = await folder.GetFileAsync(FileName);

                    IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);

                    Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;

                    return (T)serializer.Deserialize(inStream);

                }

                catch (FileNotFoundException)

                {

                    //file not existing is perfectly valid so simply return the default 

                    return default(T);

                    //throw;

                }

                catch (Exception)

                {

                    //Unable to load contents of file

                    throw;

                }

            }


            private StorageFolder GetFolder(StorageType storageType)

            {

                StorageFolder folder;

                switch (storageType)

                {

                    case StorageType.Roaming:

                        folder = appData.RoamingFolder;

                        break;

                    case StorageType.Local:

                        folder = appData.LocalFolder;

                        break;

                    case StorageType.Temporary:

                        folder = appData.TemporaryFolder;

                        break;

                    default:

                        throw new Exception(String.Format("Unknown StorageType: {0}", storageType));

                }

                return folder;

            }


            private async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)

            {

                try

                {

                    return await folder.GetFileAsync(fileName);


                }

                catch

                {

                    return null;

                }

            }

        }




    }

}


 

Introduction

Last month Microsoft announced the next version of Windows and along with it a new programming model called Windows Runtime (WinRT). Given my long-time interest in the Live Framework API which has re-emerged (sort of) in WinRT I decided to have poke around in what it had to offer. I discovered that any application written for WinRT will have access to three sandboxed folders:

  • LocalFolder
  • TemporaryFolder
  • RoamingFolder

LocalFolder and TemporaryFolder are fairly self-explanatory. RoamingFolder is where the remnants of the Live Framework API rears its head – the contents of that folder gets synced to any device on which the app is installed – thus providing the ability to sync application data between those different devices; I’m not going to go into the scenarios that this feature makes possible but I will say that I think this is one of the most exciting features about Windows 8.

As I poked and prodded at the WinRT classes provided to enable interaction with these three folders I concluded that it wasn’t exactly straightforward and figured I’d have a go at writing something a bit friendlier and hence ObjectStorageHelper<T> was born. It is, in short, a simple class that provides three basic methods:

  • void DeleteASync()
  • void SaveASync(T Object)
  • Task<T> LoadASync()

Saving an object

They simply allow you to manage storage of nearly any object (basically anything that can be serialized as XML). Here’s the code to save an object, its only two lines of code:

[TestMethod]
public void SaveObject()
{
  //Instantiate an object that we want to save
  var myPoco = new Poco() { IntProp = 1, StringProp = "one" };
  //new up ObjectStorageHelper specifying that we want to interact with the Local storage folder
  var objectStorageHelper = new ObjectStorageHelper<Poco>(StorageType.Local);
  //Save the object (via XML Serialization) to the specified folder, asynchronously
  objectStorageHelper.SaveASync(myPoco);
}

The name of the file that gets stored is determined by the name of the type T specified in ObjectStorageHelper<T> and this in turn means that only one object of type T can be stored in each of the three folders; this is by design. 
If you have a need to store multiple objects of T then you could use a List instead like this: ObjectStorageHelper<List<T>> or simply adjust the code herein so that it allows you to specify a filename.

Retrieving an object

Retrieving that object thereafter is equally as easy, just two lines of code

[TestMethod]
public async void LoadObject()
{
  //new up ObjectStorageHelper specifying that we want to interact with the Local storage folder
  var objectStorageHelper = new ObjectStorageHelper<Poco>(StorageType.Local);
  //Get the object from the storage folder
  Poco myPoco = await objectStorageHelper.LoadASync();
}

Get the goods

If you want to have a play then the code or compiled assembly is available under the MS-PL license on Codeplex at http://winrtstoragehelper.codeplex.com/. Feedback is welcome!

@jamiet