Skip to content

Quick start guide. Customers and orders. Object DBreeze

#OpKremlin edited this page Oct 23, 2023 · 19 revisions

In this guide we will create customers, prototypes of business orders for these customers and determine different search functions. NuGet reference to NetJSON and DBreeze is needed.

using System;
using System.Collections.Generic;
using DBreeze;
using DBreeze.Utils;
using System.Linq;

namespace DBreezeExamples
{
    public class CustomersAndOrders
    {
        DBreezeEngine engine = null;

        public CustomersAndOrders(DBreezeEngine eng)
        {
            this.engine = eng;

            if(engine == null)
                engine = new DBreezeEngine(@"D:\Temp\x1");

            //Setting up NetJSON serializer (from NuGet) to be used by DBreeze
            DBreeze.Utils.CustomSerializator.ByteArraySerializator = (object o) => { return NetJSON.NetJSON.Serialize(o).To_UTF8Bytes(); };
            DBreeze.Utils.CustomSerializator.ByteArrayDeSerializator = (byte[] bt, Type t) => { return NetJSON.NetJSON.Deserialize(t, bt.UTF8_GetString()); };
        }

        
        public class Customer
        {
            public long Id { get; set; } = 0;         
            public string Name { get; set; }
        }

        
        public class Order
        {
            public Order()
            {
                udtCreated = DateTime.UtcNow;
            }
            public long Id { get; set; } = 0;            
            public long CustomerId { get; set; }
            /// <summary>
            /// Order datetime creation
            /// </summary>            
            public DateTime udtCreated { get; set; }
        }


        public void Start()
        {
            //Inserting CustomerId 1
            var customer = new Customer() { Name = "Tino Zanner" };
            Test_InsertCustomer(customer);

            //Inserting some orders for this customer
            Test_InsertOrders(
                Enumerable.Range(1, 5)
                .Select(r => new Order { CustomerId = customer.Id })
                );

            //Test update order 
            Test_UpdateOrder(3);

            //Inserting CustomerId 2
            customer = new Customer() { Name = "Michael Hinze" };
            Test_InsertCustomer(customer);

            //Inserting some orders for this customer
            Test_InsertOrders(
                Enumerable.Range(1, 8)
                .Select(r => new Order { CustomerId = customer.Id })
                );


            //-------------------------- Various data retrieving

            //Getting Customer ById
            Test_GetCustomerById(2);

            //Getting Customer ByName
            Test_GetCustomerByFreeText("ichael");

            //Getting all orders
            Console.WriteLine("All orders");
            Test_GetOrdersByDateTimeRange(DateTime.MinValue, DateTime.MaxValue);

            //Getting Orders of customer 1
            Console.WriteLine("Orders of customer 1");
            Test_GetOrdersByCustomerIdAndDateTimeRange(1, DateTime.MinValue, DateTime.MaxValue);

            ////Getting Orders of customer 2
            Console.WriteLine("Orders of customer 2");
            Test_GetOrdersByCustomerIdAndDateTimeRange(2, DateTime.MinValue, DateTime.MaxValue);

        }

        /// <summary>
        /// Inserting customer
        /// </summary>
        /// <param name="customer"></param>
        void Test_InsertCustomer(Customer customer)
        {
            try
            {
                /*
                    We are going to store all customers in one table
                    Later we are going to search customers by their IDs and Names
                */

                using (var t = engine.GetTransaction())
                {
                    //Documentation https://goo.gl/Kwm9aq
                    //This line with a list of tables we need in case if we modify more than 1 table inside of transaction
                    t.SynchronizeTables("Customers", "TS_Customers");

                    bool newEntity = customer.Id == 0;
                    if(newEntity)
                        customer.Id = t.ObjectGetNewIdentity<long>("Customers");

                    //Documentation https://goo.gl/YtWnAJ
                    t.ObjectInsert("Customers", new DBreeze.Objects.DBreezeObject<Customer>
                    {
                        NewEntity = newEntity,
                        Entity = customer,
                        Indexes = new List<DBreeze.Objects.DBreezeIndex>
                        {
                            //to Get customer by ID
                            new DBreeze.Objects.DBreezeIndex(1,customer.Id) { PrimaryIndex = true },
                        }
                    }, false);

                    //Documentation https://goo.gl/s8vtRG
                    //Setting text search index. We will store text-search 
                    //indexes concerning customers in table "TS_Customers".
                    //Second parameter is a reference to the customer ID.
                    t.TextInsert("TS_Customers", customer.Id.ToBytes(), customer.Name);

                    //Committing entry
                    t.Commit();
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Inserting orders
        /// </summary>
        /// <param name="orders"></param>
        void Test_InsertOrders(IEnumerable<Order> orders)
        {
            try
            {
                /*
                We are going to store all orders from all customers in one table.
                Later we are planning to search orders:
                    1. by Order.Id
                    2. by Order.udtCreated From-To
                    3. by Order.CustomerId and Order.udtCreated From-To
                */

                using (var t = engine.GetTransaction())
                {
                    //This line with a list of tables we need in case if we modify morethen 1 table inside of transaction
                    //Documentation https://goo.gl/Kwm9aq
                    t.SynchronizeTables("Orders");

                    foreach (var order in orders)
                    {
                        bool newEntity = order.Id == 0;
                        if (newEntity)
                            order.Id = t.ObjectGetNewIdentity<long>("Orders");
                        
                        t.ObjectInsert("Orders", new DBreeze.Objects.DBreezeObject<Order>
                        {
                            NewEntity = newEntity,
                            Indexes = new List<DBreeze.Objects.DBreezeIndex>
                             {
                                 //to Get order by ID
                                 new DBreeze.Objects.DBreezeIndex(1,order.Id) { PrimaryIndex = true },
                                 //to get orders in specified time interval
                                 new DBreeze.Objects.DBreezeIndex(2,order.udtCreated) { AddPrimaryToTheEnd = true }, //AddPrimaryToTheEnd by default is true
                                 //to get orders in specified time range for specific customer
                                 new DBreeze.Objects.DBreezeIndex(3,order.CustomerId, order.udtCreated)
                             },
                            Entity = order  //Setting entity
                        }, false);  //set last parameter to true, if batch operation speed unsatisfactory
                    }

                    //Committing all changes
                    t.Commit();
                    
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Updating order 3
        /// </summary>
        /// <param name="orderId"></param>
        void Test_UpdateOrder(long orderId)
        {
            try
            {  

                using (var t = engine.GetTransaction())
                {
                    //This line with a list of tables we need in case if we modify morethen 1 table inside of transaction
                    //Documentation https://goo.gl/Kwm9aq
                    t.SynchronizeTables("Orders");

                    var ord = t.Select<byte[], byte[]>("Orders", 1.ToIndex(orderId)).ObjectGet<Order>();
                    if (ord == null)
                        return;

                    ord.Entity.udtCreated = new DateTime(1977, 1, 1);
                    ord.Indexes = new List<DBreeze.Objects.DBreezeIndex>()
                    {
                          //to Get order by ID
                                 new DBreeze.Objects.DBreezeIndex(1,ord.Entity.Id) { PrimaryIndex = true },
                                 //to get orders in specified time interval
                                 new DBreeze.Objects.DBreezeIndex(2,ord.Entity.udtCreated), //AddPrimaryToTheEnd by default is true
                                 //to get orders in specified time range for specific customer
                                 new DBreeze.Objects.DBreezeIndex(3,ord.Entity.CustomerId, ord.Entity.udtCreated)
                    };

                    t.ObjectInsert<Order>("Orders", ord, false);
                    
                    //Committing all changes
                    t.Commit();

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        void Test_GetOrdersByDateTimeRange(DateTime from, DateTime to)
        {
            Console.WriteLine("--------Test_GetOrdersByDateTimeRange--------");
            try
            {
                using (var t = engine.GetTransaction())
                {

                    //Documentation https://goo.gl/MbZAsB
                    foreach (var row in t.SelectForwardFromTo<byte[], byte[]>("Orders",
                        2.ToIndex(from, long.MinValue), true,
                        2.ToIndex(to, long.MaxValue), true))
                    {
                        var obj = row.ObjectGet<Order>();
                        if (obj != null)
                            Console.WriteLine(obj.Entity.Id + " " + obj.Entity.udtCreated.ToString("dd.MM.yyyy HH:mm:ss.fff") + " " + obj.Entity.CustomerId);
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.WriteLine("-------------------------------------");
        }


        void Test_GetOrdersByCustomerIdAndDateTimeRange(long customerId, DateTime from, DateTime to)
        {
            Console.WriteLine("--------Test_GetOrdersByCustomerIdAndDateTimeRange--------");
            try
            {
                using (var t = engine.GetTransaction())
                {


                    foreach (var row in t.SelectForwardFromTo<byte[], byte[]>("Orders", 
                        3.ToIndex(customerId, from, long.MinValue), true,
                        3.ToIndex(customerId, to, long.MaxValue), true))
                    {
                        var obj = row.ObjectGet<Order>();
                        if (obj != null)
                            Console.WriteLine(obj.Entity.Id + " " + obj.Entity.udtCreated.ToString("dd.MM.yyyy HH:mm:ss.fff") + " " + obj.Entity.CustomerId);                        
                    }
                    
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.WriteLine("-------------------------------------");
        }


        void Test_GetCustomerById(long customerId)
        {           
            Console.WriteLine("--------Test_GetCustomerById--------");
            try
            {
                using (var t = engine.GetTransaction())
                {
                    var obj = t.Select<byte[], byte[]>("Customers", 1.ToIndex(customerId)).ObjectGet<Customer>();
                    if (obj != null)
                        Console.WriteLine(obj.Entity.Id + " " + obj.Entity.Name);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.WriteLine("-------------------------------------");
        }

        /// <summary>
        /// Test_GetCustomerByFreeText
        /// </summary>
        /// <param name="text"></param>
        void Test_GetCustomerByFreeText(string text)
        {
            Console.WriteLine("--------Test_GetCustomerByFreeText--------");
            try
            {
                using (var t = engine.GetTransaction())
                {
                    foreach (var doc in t.TextSearch("TS_Customers").BlockAnd(text).GetDocumentIDs())
                    {
                        var obj = t.Select<byte[], byte[]>("Customers", 1.ToIndex(doc)).ObjectGet<Customer>();
                        if (obj != null)
                            Console.WriteLine(obj.Entity.Id + " " + obj.Entity.Name);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            Console.WriteLine("-------------------------------------");
        }
    }
}
Test_GetCustomerById
2 Michael Hinze

Test_GetCustomerByFreeText
2 Michael Hinze

All orders
Test_GetOrdersByDateTimeRange
3 01.01.1977 00:00:00.000 1
1 24.03.2017 10:26:03.411 1
2 24.03.2017 10:26:03.517 1
4 24.03.2017 10:26:03.518 1
5 24.03.2017 10:26:03.518 1
6 24.03.2017 10:26:04.191 2
7 24.03.2017 10:26:04.191 2
8 24.03.2017 10:26:04.191 2
9 24.03.2017 10:26:04.191 2
10 24.03.2017 10:26:04.191 2
11 24.03.2017 10:26:04.191 2
12 24.03.2017 10:26:04.191 2
13 24.03.2017 10:26:04.191 2

Orders of customer 1
Test_GetOrdersByCustomerIdAndDateTimeRange
3 01.01.1977 00:00:00.000 1
1 24.03.2017 10:26:03.411 1
2 24.03.2017 10:26:03.517 1
4 24.03.2017 10:26:03.518 1
5 24.03.2017 10:26:03.518 1

Orders of customer 2
Test_GetOrdersByCustomerIdAndDateTimeRange
6 24.03.2017 10:26:04.191 2
7 24.03.2017 10:26:04.191 2
8 24.03.2017 10:26:04.191 2
9 24.03.2017 10:26:04.191 2
10 24.03.2017 10:26:04.191 2
11 24.03.2017 10:26:04.191 2
12 24.03.2017 10:26:04.191 2
13 24.03.2017 10:26:04.191 2
Clone this wiki locally