//#define WP

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

using iBoxDB.LocalServer;
using iBoxDB.LocalServer.IO;


#if WP
using System.IO.IsolatedStorage;
#endif

// for iBoxDB v1.3

    //Console.WriteLine(iBoxDB.Test.V13.ProgramTest.PMain().ToString());
    //Console.WriteLine(iBoxDB.Test.V13.MMS.MasterSlave.PMain().ToString() );
    //Console.WriteLine(iBoxDB.Test.V13.MMS.MasterMaster.PMain().ToString());
   // iBoxDB.Test.V13.InsertSpeed.ProgramTest.ConsoleMain();
namespace iBoxDB.Test.V13
{
    public abstract class IDClass
    {
        public long ID { get; set; }
    }
        
    public class Member : IDClass
    {
        public static readonly byte IncTableID = 0;

        [BoxLength(typeof(char),20)]
        public string Name { get; set; }

        public DateTime RegTime;

        [BoxLength(256)]
        public string[] Tags { get; set; }

        public decimal Amount { get; set; }
    }

    //Dynamic Object
    [BoxLength( 1024 )]
    public class Product : Dictionary<string,object>
    {

        public int Type
        {
            get
            {
                return (int)this["Type"];
            }
            set
            {
                this["Type"] = value;
            }
        }

        public Guid UID
        {
            get
            {
                return (Guid)this["UID"];
            }
            set
            {
                this["UID"] = value;
            }
        }


        public string Name
        {
            get
            {
                return (string)this["Name"];
            }
            set
            {
                this["Name"] = value;
            }
        }
    }


    public class QueryArray : IFunction
    {
        string match;
        public QueryArray( string match )
        {
            this.match = match;
        }


        public object Execute(int argCount, object[] args)
        {
            var tags = (string[])args[0];
            if (tags == null) { return false; }
            foreach (var t in tags)
            {
                if (t == match)
                {
                    return true;
                }
            }
            return false;
        }
    }
  

    class C1BaseServer : LocalDataBaseServer
    {
        public class C1Config :
#if WP
 BoxIsolatedStorageFileStreamConfig
#else
            BoxFileStreamConfig
#endif
        {
            public C1Config(string name)
                : base()
            {
                this.EnsureTable<Member>("Member", "ID");
                this.EnsureIndex<Member>("Member", false, "Name");
                this.EnsureTable<Product>("Product", "Type" , "UID");

                //test insert
                this.EnsureTable<Member>("TSpeed", "ID");
                // Cache Setting , Minimum is 1
                //this.CachePageCount = 1025 * 5;
                //this.SessionCount =

                // Minimum is 0 , preAllocate FileSize
                //this.FileIncSize = ;
            }
        }

        public static string DBName = "DB.box";
        protected override DataBaseConfig BuildDataBaseConfig(string name)
        {
            if (name.Equals(DBName))
            {
                return new C1Config(DBName);
            }
            throw new NotImplementedException();
        }
        public static void DeleteForTest()
        {
            
#if WP
             DBDebug.DDebug.DeleteDBFiles( DBName, true);
#else
            DBDebug.DDebug.DeleteDBFiles(DBName);
#endif
            System.Threading.Thread.Sleep(200);
        }
    }


    class ProgramTest
    {
        public static StringBuilder PMain()
        {
            //Monitor
            //BoxSystem.Performance.Print = (msg) =>
            //{
            //    Console.WriteLine(msg);
            //};

            StringBuilder sb = new StringBuilder();
            try
            {
                C1BaseServer.DeleteForTest();               
                using (var server = new C1BaseServer())
                {
                    using (var db = server.GetInstance(C1BaseServer.DBName))
                    {
                        using (var box = db.Cube())
                        {
                            // insert member & product
                            box.Insert("Member",
                                new Member() {  
                                    ID=box.NewId( Member.IncTableID,1) ,
                                    Name = "Andy",
                                    RegTime = new DateTime(2013,1,2),
                                    Tags = new string[]{ "Nice" , "Strong" }
                                }
                                );
                            box.Insert("Member",
                             new Member()
                             {
                                 ID = box.NewId(Member.IncTableID, 1),
                                 Name = "Kelly",
                                 RegTime = new DateTime(2013, 1, 3),
                                 Tags = new string[] { "Gamer" }
                             }
                             );
                         
                            // Dynamic Column 
                            Product game = new Product()
                            {
                                Type = 8,
                                UID = Guid.Parse("{22222222-0000-0000-0000-000000000000}"),
                                Name = "MoonFlight"
                            };
                            game["GameType"] = "ACT";
                            box.Insert("Product", game);
 

                            box.Commit().Assert();
                        }


                        using (var box = db.Cube())
                        {
                            // SQL like
                            //  > < >= <=  == != & | () []
                            var m = GetFrist(box.BSelect<Member>("from Member where Name==?", "Kelly"));
                            sb.Append("Kelly RegTime " + m.RegTime.ToShortDateString() + "\r\n");
                            m.Name = "Kelly J";
                            m.Amount = 100;
                            box.Bind("Member", m.ID).Update(m);
                            box.Commit().Assert();
                        }
                        using (var box = db.Cube())
                        {
                            var m = GetFrist(box.BSelect<Member>("from Member where Name==?", "Kelly J"));
                            sb.Append( "Updated 1: " +  m.Name + "  " + m.Amount  + "\r\n");

                            m.Amount += new decimal(99.99);
                            // not update index
                            box.UpdateNoIndex("Member", m);
                            box.Commit().Assert();
                        }
                        using (var box = db.Cube())
                        {
                            var m = GetFrist(box.BSelect<Member>("from Member where Name==?", "Kelly J"));
                            sb.Append("Updated 2: " + m.Name + "  " + m.Amount + "\r\n");
                        }

                        using (var box = db.Cube())
                        {
                            // Key-Value Style , CoupleKey Supported
                            var cs = box
                                .Bind("Product", 8, Guid.Parse("{22222222-0000-0000-0000-000000000000}"))
                                .Select<Product>();
                            sb.Append( "Product Name " + cs.Name +   "  " + cs["GameType"] + "\r\n" );
                        }

                        using (var box = db.Cube())
                        {
                            //Custom QueryFunction  
                            // [] <= call IFunction Interface
                            // [A,B] <=  Fields will be passed  
                           var list = box.BSelect<Member>("from Member where [Tags]", new QueryArray("Strong"));
                           sb.Append("The Strong one is ");
                           foreach (var m in list)
                           {
                               sb.Append( "'" + m.Name + "'\r\n" );
                           }
                        }
                        //

                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.Message + "\r\n");
                sb.Append(ex.StackTrace + "\r\n");
            }
            return sb;
        }

        private static T GetFrist<T>(IEnumerable<T> list)
        {
            foreach (var o in list)
            {
                return o;
            }
            return default(T);
        }
    }
}


namespace iBoxDB.Test.V13.MMS
{
    using iBoxDB.LocalServer.Replication;


    class ServerID
    {
        public const int MasterA_Address = 10;
        public const int MasterB_Address = 20;

        //  negative number
        public const int SlaveA_Address = -10;
    }

    class MMSBaseServer : C1BaseServer
    {
        public static string SlaveA_DBName = "DB_SlaveA.box";

        public static string MasterA_DBName = C1BaseServer.DBName;
        public static string MasterB_DBName = "DB_MasterB.box";


        public static void MMSDeleteForTest()
        {
            C1BaseServer.DeleteForTest();

#if WP
             DBDebug.DDebug.DeleteDBFiles( SlaveA_DBName, true);
             DBDebug.DDebug.DeleteDBFiles( MasterB_DBName, true);
#else
            DBDebug.DDebug.DeleteDBFiles(SlaveA_DBName);
            DBDebug.DDebug.DeleteDBFiles(MasterB_DBName);
#endif
            System.Threading.Thread.Sleep(200);
        }

        protected override DataBaseConfig BuildDataBaseConfig(string name)
        {
            if (name == SlaveA_DBName)
            {
                return new C1Config(name);
            }
            if (name == MasterB_DBName)
            {
                return new C1Config(name);
            }
            return base.BuildDataBaseConfig(name);
        }
        protected override IBoxRecycler BuildBoxRecycler(string name, DataBaseConfig config)
        {
            if (name == MasterA_DBName)
            {
                return new InMemoryBoxRecycler(name, config);
            }
            if (name == MasterB_DBName)
            {
                return new InMemoryBoxRecycler(name, config);
            }
            return base.BuildBoxRecycler(name, config);
        }
    }

    class Package
    {
        public Socket Socket;
        public byte[] OutBox;
    }
    class InMemoryBoxRecycler : IBoxRecycler
    {
        List<Package> qBuffer;
        public InMemoryBoxRecycler(string name, DataBaseConfig config)
        {
            name = QBuffer.GetBufferName(name);
            qBuffer = new List<Package>();
        }

        public void OnReceived(Socket socket, byte[] outBox, bool normal)
        {
            lock (qBuffer)
            {
                qBuffer.Add(
                    new Package { Socket = socket, OutBox = outBox }
                    );
            }
        }

        public List<Package> GetPackage()
        {
            return qBuffer;
        }

        public void Dispose()
        {
            qBuffer = null;
        }
    }
    

    class MasterSlave
    {
        public static StringBuilder PMain()
        {       
            StringBuilder sb = new StringBuilder();
            try
            {
                MMSBaseServer.MMSDeleteForTest();
                using (var server = new MMSBaseServer())
                {
                    var masterA = server.GetInstance(MMSBaseServer.MasterA_DBName, ServerID.MasterA_Address);
                    var slaveA = server.GetInstance(MMSBaseServer.SlaveA_DBName, ServerID.SlaveA_Address);

                    using (var box = masterA.Cube())
                    {
                        for (var i = 0; i < 3; i++)
                        {
                            box.Insert("Member",
                              new Member()
                              {
                                  ID = box.NewId(Member.IncTableID, 1),
                                  Name = "LN " + i
                              }
                              );
                        }
                        box.Commit().Assert();
                    }
                    
                    // collect box post to slave
                    var recycler = (InMemoryBoxRecycler)masterA.GetBoxRecycler();
                    lock (recycler.GetPackage())
                    {
                        foreach (var p in recycler.GetPackage())
                        {
                            if (p.Socket.SourceAddress == ServerID.MasterA_Address)
                            {
                                p.OutBox.SlaveReplicate(slaveA).Assert();
                            }
                        }
                        recycler.GetPackage().Clear();
                    }

                    // checking
                    sb.Append("\r\nMasterA Address is " + masterA.LocalAddress + " \r\n");
                    using (var box = masterA.Cube())
                    {
                        foreach (var o in box.Select<Member>("from Member", null))
                        {
                            sb.Append(o.Name + " , ");
                        }
                    }
                    sb.Append("\r\nSlaveA Address is " + slaveA.LocalAddress + " \r\n");
                    using (var box = slaveA.Cube())
                    {
                        foreach (var o in box.Select<Member>("from Member", null))
                        {
                            sb.Append(o.Name + " , ");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.ToString() + "\r\n");
            }
            return sb;
        }

    }



    class MasterMaster
    {
        public static StringBuilder PMain()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                MMSBaseServer.MMSDeleteForTest();
                using (var server = new MMSBaseServer())
                {
                    var masterA = server.GetInstance(MMSBaseServer.MasterA_DBName, ServerID.MasterA_Address);
                    var masterB = server.GetInstance(MMSBaseServer.MasterB_DBName , ServerID.MasterB_Address);

                    // send to MasterB_Address
                    using (var box = masterA.Cube( ServerID.MasterB_Address ))
                    {
                        for (var i = 0; i < 3; i++)
                        {
                            box.Insert("Member",
                              new Member()
                              {                                  
                                  ID = box.NewId(Member.IncTableID, 1) * 1000 + ServerID.MasterA_Address,
                                  Name = "A" + i
                              }
                              );
                        }
                        box.Commit().Assert();
                    }
                    //send to MasterA_Address
                    using (var box = masterB.Cube(ServerID.MasterA_Address))
                    {
                        for (var i = 0; i < 3; i++)
                        {
                            box.Insert("Member",
                              new Member()
                              {
                                  ID = box.NewId(Member.IncTableID, 1) * 1000 + ServerID.MasterB_Address,
                                  Name = "B" + i
                              }
                              );
                        }
                        box.Commit().Assert();
                    }

                    // collect
                    List<Package> buffer;
                    var recycler = (InMemoryBoxRecycler)masterA.GetBoxRecycler();                    
                    lock (recycler.GetPackage())
                    {
                        buffer = new List<Package>(recycler.GetPackage());
                        recycler.GetPackage().Clear();
                    }
                    recycler = (InMemoryBoxRecycler)masterB.GetBoxRecycler();
                    lock (recycler.GetPackage())
                    {
                        buffer.AddRange(recycler.GetPackage());
                        recycler.GetPackage().Clear();
                    }
                    foreach (var p in buffer)
                    {
                        if (p.Socket.DestAddress == ServerID.MasterA_Address)
                        {
                            p.OutBox.MasterReplicate(masterA);
                        }
                        if (p.Socket.DestAddress == ServerID.MasterB_Address)
                        {
                            p.OutBox.MasterReplicate(masterB);
                        }
                    }

                    // checking
                    sb.Append("\r\nMasterA Address is " + masterA.LocalAddress + " \r\n");
                    using (var box = masterA.Cube())
                    {
                        foreach (var o in box.Select<Member>("from Member", null))
                        {
                            sb.Append(o.Name + " , ");
                        }
                    }
                    sb.Append("\r\nMasterB Address is " + masterB.LocalAddress + " \r\n");
                    using (var box = masterB.Cube())
                    {
                        foreach (var o in box.Select<Member>("from Member", null))
                        {
                            sb.Append(o.Name + " , ");
                        }
                    }                    
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.ToString() + "\r\n");
            }
            return sb;
        }
    }

}


namespace iBoxDB.Test.V13.InsertSpeed
{
#if !WP
    using System.Threading.Tasks;
    using System.Diagnostics;
    using System.Linq;
#endif

    class ProgramTest
    {
        public static void ConsoleMain()
        {
#if !WP
            try
            {
                C1BaseServer.DeleteForTest();
                using (var server = new C1BaseServer())
                {
                    using (var db = server.GetInstance(C1BaseServer.DBName))
                    {
                        var threadCount = 20000;
                        var objectCount = 10;
                        Console.WriteLine("\r\nBegin Insert " + (threadCount*objectCount).ToString("#,#")  );
                        var sw = new Stopwatch();
                        sw.Start();
                        Parallel.For(0, threadCount,
                            (i) =>
                            {
                                using (var box = db.Cube())
                                {
                                    for (var o = 0; o < objectCount; o++)
                                    {
                                        var m = new Member
                                        {
                                            ID = box.NewId(0, 1),
                                            Name = i.ToString() + "_" + o.ToString()
                                        };
                                        box.Insert("TSpeed", m);
                                    }                                    
                                    box.Commit().Assert();
                                }
                            }
                        );
                        var sec = sw.Elapsed.TotalSeconds;
                        var avg = (threadCount * objectCount) / sec;
                        Console.WriteLine( "Elapsed " + (int)sec + ", AVG Insert " + avg.ToString("#,#") + " o/sec" );

                        //using (var box = db.Cube())
                        //{
                        //    var c = box.BSelect<object>("from TSpeed").Count();
                        //    Console.WriteLine(c.ToString("#,#"));
                        //    if (c != (threadCount * objectCount))
                        //    {
                        //        throw new Exception("unreachable");
                        //    }                            
                        //}
                    }
                }

                Console.WriteLine("Enter");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
#endif
        }
    }
}

Last edited Jan 24, 2013 at 7:25 AM by iboxdb, version 3

Comments

No comments yet.