设为首页 收藏本站
查看: 605|回复: 0

Windows Phone 7 XML IsolatedStorage Example

[复制链接]

尚未签到

发表于 2015-5-12 13:33:53 | 显示全部楼层 |阅读模式
  For one of the apps I have been working on, I needed to persist a List of T objects across sessions. They are simple objects with simple properties, so I decided to use XML. However, since WP7 is a new platform, there’s not a lot of information out there on what is a good best practice.
  It turns out for simple situations like mine, serializing objects into XML and writing that to file is by far the easiest way to do it.
  Let’s examine a scenario.
The App
  This is not an app I am working on, but it is basically the same thing.
  Let’s say that you want to track your jogs. Starting simple, you decide to track the following properties:

  • RouteID : int
  • Duration : TimeSpan (we will encounter an interesting serialization bug with TimeSpan as well)
  • Date : DateTime
  • Distance (miles) : float
  Of course, we won’t attempt to build all of this here, but rather, focus on the storage aspect of it.
The “Jog” Object
  You will persist a list of these objects to be able to view them historically. This is what a Jog object might look like. Note the extra property, DurationXml, with its special attributes – this exists because XmlSerializer does not properly serialize TimeSpan objects.
  

DSC0000.gif DSC0001.gif 代码

public class Jog
    {
        private TimeSpan _duration = new TimeSpan();
        public DateTime Date { get; set; }
        [XmlIgnore]
        public TimeSpan Duration
        {
            get { return _duration; }
            set { _duration = value; }
        }
        // HACK: This property only exists for XML serialization.
        // It gets serialized as a  tag.
        [XmlElement("Duration", DataType="duration")]
        public string DurationXml
        {
            get
            {
                return XmlConvert.ToString(_duration);
            }
            set
            {
                if (value == null)
                {
                    _duration = TimeSpan.Zero;
                    return;
                }
                TimeSpan newDuration = XmlConvert.ToTimeSpan(value);
                if (_duration == newDuration)
                    return;
                _duration = newDuration;
            }
        }
        public int RouteID { get; set; }
        public float Distance { get; set; }
    }
  
  
  
  Note the hackery around the Duration and DurationXml properties.
Jog List
  For the purposes of this app, you’d have a List of Jog objects: List which you keep as a static on the App class and maintain it there. You’d then create some methods in the App class that would help out with storage, and then call them from Application_Closing, Application_Launching, and Activated/Deactivated as you handle tombstoning and deactivation.
Storage Helper
  Then, you might write a class like this which helps with storage, and keep it statically on the App class. All you have to do is call XmlSerializer.Serialize(object) and XmlHelper.Deserialize(xml) to manage the saving/loading of your object list. Put together, it looks like this:
  

代码

public class StorageHelper
    {
        private const string FILE_NAME = "Jogs.xml";
        public List LoadJogs()
        {
            List jogs = new List();
            TextReader reader = null;
            try
            {
                IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream file = isoStorage.OpenFile(FILE_NAME, FileMode.OpenOrCreate);
                reader = new StreamReader(file);
                 XmlSerializer xs = new XmlSerializer(typeof(List));
                feedings.AddRange((List)xs.Deserialize(reader));
                reader.Close();               
            }
            catch
            {
               
            }
            finally
            {
                if (reader != null)
                    reader.Dispose();               
            }
            return jogs;
        }
        public void SaveJogs(List jogs)
        {
            TextWriter writer = null;
            try
            {
                IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream file = isoStorage.OpenFile(FILE_NAME, FileMode.Create);
                writer = new StreamWriter(file);
                XmlSerializer xs = new XmlSerializer(typeof(List));
                xs.Serialize(writer, jogs);
                writer.Close();
            }
            catch
            {
            }
            finally
            {
                if (writer != null)
                    writer.Dispose();
            }
        }
        public StorageHelper()
        {
        }
    }  
  
  
Don’t Forget Your References
  One thing to note here is that several of the Xml classes won’t magically work with IntelliSense. You need to add references to System.Xml and System.Xml.Serialization for all this good stuff to work.
  I’ll be posting an example Jog Tracker application that uses isolated storage in the coming weeks, but for now, this should be enough to get you started.
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-66295-1-1.html 上篇帖子: Windows Phone 7 Tip (14) 下篇帖子: 基于Visua C++2010 与 Windows 7 SDK开发windows7 Shell应用(1)-搜索文件夹
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表