Friday, 19 November 2010

WPF data storage without a database

In some smaller programs its not always beneficial to supply a sql database especially if you are only using one or two sets of information i.e. contacts and addresses.

First create a class for a set of information, in this case I have setup a Contact class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example.Model
{
    [Serializable]
    public class Contact : Notifier
    {
        private Guid _id = Guid.Empty;
        private string _firstNames;
        private string _surname;
        private string _homePhone;
        private string _workPhone;
        private string _mobilePhone;
        private string _imagePath;
        private string _jobTitle;
        private string _organization;
        private string _primaryEmail;
        private string _secondaryEmail;

        public Guid Id
        {
            get { return _id; }
            set { _id = value; }
        }
        public string FirstNames
        {
            get { return _firstNames; }
            set { _firstNames = value; }
        }
        public string Surname
        {
            get { return _surname; }
            set { _surname = value; }
        }
        public string HomePhone
        {
            get { return _homePhone; }
            set { _homePhone = value; }
        }
        public string WorkPhone
        {
            get { return _workPhone; }
            set { _workPhone = value; }
        }
        public string MobilePhone
        {
            get { return _mobilePhone; }
            set { _mobilePhone = value; }
        }
        public string ImagePath
        {
            get { return _imagePath; }
            set { _imagePath = value; }
        }
        public string JobTitle
        {
            get { return _jobTitle; }
            set { _jobTitle = value; }
        }
        public string Organization
        {
            get { return _organization; }
            set { _organization = value; }
        }
        public string PrimaryEmail
        {
            get { return _primaryEmail; }
            set { _primaryEmail = value; }
        }
        public string SecondaryEmail
        {
            get { return _secondaryEmail; }
            set { _secondaryEmail = value; }
        }

        public override bool Equals(object obj)
        {
            Contact other = obj as Contact;
            return other != null && other.Id == Id;            
        }
    }
}
Then setup our class for saving data, I have called it DataRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Example.Model
{
    public class DataRepository
    {
        private List _contactStore;       
        private readonly string _stateFile;

        public DataRepository()
        {
            _stateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "contacts.state");

            Deserialize();
        }

        public void SaveContact(Contact contact)
        {
            if (contact.Id == Guid.Empty)
                contact.Id = Guid.NewGuid();

            if (!_contactStore.Contains(contact))
                _contactStore.Add(contact);

            Serialize();
        }
        public void DeleteContact(Contact contact)
        {
            _contactStore.Remove(contact);
            Serialize();
        }
        public List FindAllContacts()
        {
            return new List(_contactStore);
        }
        private void Serialize()
        {
            using (FileStream stream = File.Open(_stateFile, FileMode.OpenOrCreate))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, _contactStore);
            }
        }

        private void Deserialize()
        {
            if (File.Exists(_stateFile))
            {
                using (FileStream stream = File.Open(_stateFile, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    _contactStore = (List)formatter.Deserialize(stream);
                }
            }
            else _contactStore = new List();            
        }
        
    }
}
Break It Down

On the first line of the class member it creates a new string for a file called contacts.state: _stateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "contacts.state");

In the Deserialize function this effectively checks to see if the file exists by this name and if so creates a filestream to extract the data.

Whenever a save or delete is performed the Serialize function is called which creates the file if it does not exist and adds the contact list to the file.

How to use
Easy simply create a new DataRepository class, load the current data and call the functions as required:
DataRepository _dataRepository;  // define class
ObservableCollection _currentContacts = new ObservableCollection(_dataRepository.FindAllContacts()); // load current data and use however you wish
Saving a record from a pre defined Contact class
if (!_currentContacts.Contains(contact)) // assumes you have created a new Contact class already
     _currentContacts.Add(contact);
    _dataRepository.SaveContact(contact);

Let me know if you have any more questions or get stuck.

No comments:

Post a Comment