2011年11月1日

[NoSQL]Sterling Database

最近在survey之後案子也許會用到的NoSQL Solution, 這是目前在CodePlex上滿受歡迎的一個解決方案. Sterling NoSQL OODB for .Net

首先, 撰寫自己的Sterling Service如下

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Wintellect.Sterling.Database;
using Wintellect.Sterling;
namespace MoneyBook.Data.DBHelpers
{
    public class MBookDBService : IApplicationService, IApplicationLifetimeAware, IDisposable
    {
        private SterlingEngine _engine = null;
        private SterlingDefaultLogger _logger = null;
        public ISterlingDatabaseInstance Database { get; private set; }
        #region IApplicationService Members
        public void StartService(ApplicationServiceContext context)
        {
            if (System.ComponentModel.DesignerProperties.IsInDesignTool)
                return;
            if (_engine != null)
            {
                StopService();
                Dispose();
            }
            _engine = new SterlingEngine();
            
        }
        public void StopService()
        {
            
        }
        #endregion
        #region IApplicationLifetimeAware Members
        public void Exited()
        {
            Dispose();
        }
        public void Exiting()
        {
            if (System.ComponentModel.DesignerProperties.IsInDesignTool)
            {
                return;
            }
            if (System.Diagnostics.Debugger.IsAttached && _logger != null)
            {
                _logger.Detach();
            }
        }
        public void Started()
        {
        }
//remove first lunch flag
        private static void DeleteFirstLunchFlag()
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFile file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (file.FileExists("/MBook/lunched.txt"))
                {
                    file.DeleteFile("/MBook/lunched.txt");
                }
            }
        }
//Check if this is the first time we lunching this database instance
        private static bool IsFirstLunch()
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFile file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                return file.FileExists("/MBook/lunched.txt");
            }
        }
//Set first lunch flag
        private static void SetFirstLunchFlag()
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFile file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!file.FileExists("/MBook/lunched.txt"))
                {
                    try
                    {
                        file.CreateFile("/MBook/lunched.txt").Write(new byte[] { 0x31 }, 0, 1);
                    }
                    catch { }
                }
            }
        }
        public void Starting()
        {
            if (System.ComponentModel.DesignerProperties.IsInDesignTool)
                return;
            _engine.Activate();
            Database = _engine.SterlingDatabase.RegisterDatabase<MBookDatabase>();
//Check if this is the first time, if so, setup initial data
//--NOTE-- this is only for testing purpose
            if (IsFirstLunch())
            {
                var db = (Database as MoneyBook.Data.DBHelpers.MBookDatabase);
                var cs = db.GetInitCategories();
                foreach (var c in cs)
                {
                    Database.Save(c);
                }
                SetFirstLunchFlag();
            }
        }
        #endregion
        #region IDisposable Members
        public void Dispose()
        {
            if (_engine != null)
            {
                _engine.Dispose();
                _engine = null;
            }
//Also, delete the flag, this is only for testing purpose
            DeleteFirstLunchFlag();
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}


然後撰寫自己的Database



public partial class MyDatabase: BaseDatabaseInstance
    {
//override this method to create our own table definations
        protected override System.Collections.Generic.List<ITableDefinition> RegisterTables()
        {
            System.Collections.Generic.List<ITableDefinition> tables = new System.Collections.Generic.List<ITableDefinition>();
            //Add book table
            tables.Add(CreateTableDefinition<MBook, string>(x => x.BookID));
            //Add record table
            tables.Add(CreateTableDefinition<MRecord, string>(x => x.ID).WithIndex<MRecord, DateTime, string>("Index_MRecord_Date", x => x.Date));
            //Add category table
            tables.Add(CreateTableDefinition<MCategory, string>(x => x.CategoryID));
            //Add subcategory table
            tables.Add(CreateTableDefinition<MSubcategory, string>(x => x.SubcategoryID));
            return tables;
        }


使用前必須在App.xml中註冊為ApplicationLifetimeObject



<Application 
    x:Class="MoneyBook.UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:MBook="clr-namespace:MyDatabasae.Data.DBHelpers;assembly=MyDatabase.Data"
    xmlns:Sterling="clr-namespace:Wintellect.Sterling;assembly=Wintellect.Sterling.WindowsPhone">
    <!--Application Resources-->
    <Application.Resources>
    </Application.Resources>
    <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
        <MBook:MBookDBService/><!--Here-->
    </Application.ApplicationLifetimeObjects>
<!---->
</Application>


查詢資料



return MDBInstance.Query<MyDatabase.MCategory, string>().Select(x => x.LazyValue.Value).ToList();

沒有留言:

Blog Archive

About Me