Beispiel #1
0
 /// <summary>
 /// Сохранение автора в БД
 /// </summary>
 /// <param name="author"></param>
 public void SaveAuthor(Author author)
 {
     if (server == null)
     {
         return;
     }
     try
     {
         using (IObjectContainer documentStore = server.OpenClient())
         {
             var _author = documentStore
                           .Query <AuthorDb4o>(x => x != null && x.Id == author.Id)
                           .FirstOrDefault();
             if (_author != null)
             {
                 _author.author = author;
                 documentStore.Delete(_author);
                 _author.author.URL = _author.author.URL.Replace("zhurnal.lib.ru", "samlib.ru");
                 documentStore.Store(_author);
             }
             else
             {
                 documentStore.Store(new AuthorDb4o {
                     Id = author.Id, author = author
                 });
             }
             documentStore.Commit();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Ошибка сохранения данных автора в БД." + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Beispiel #2
0
        private void FillRelationsBetweenEntities()
        {
            var types = _entitityTypes
                        .OrderByDescending(kv => kv.Value.TotalRowsCount)
                        .Select(kv => kv.Key)
                        .ToList();

            if (!UseParallelMode)
            {
                var blder = new StringBuilder();

                var db4OClient = UseClient ? _embeddedContainer : _emmbededServer.OpenClient();

                foreach (var entityType in types)
                {
                    var startTime = DateTime.Now;

                    OnStepBeforeFilled(entityType, MigrationStep.FillingRelations, startTime);

                    try
                    {
                        FillRelationsOfEntity(entityType, db4OClient, EntitiesStorePool);
                    }
                    catch (Exception excp)
                    {
                        db4OClient.Rollback();
                        blder.AppendLine(entityType.ToString() + " " + excp.Message);
                    }

                    OnStepAfterFilled(entityType, MigrationStep.FillingRelations, startTime, DateTime.Now);
                }

                db4OClient.Close();
                db4OClient.Dispose();

                return;
            }

            types.EachParallel(delegate(Type entityType)
            {
                var db4OParallelClient = UseClient ? _embeddedContainer : _emmbededServer.OpenClient();

                var startTime = DateTime.Now;
                OnStepBeforeFilled(entityType, MigrationStep.FillingRelations, startTime);
                FillRelationsOfEntity(entityType, db4OParallelClient, EntitiesStorePool);
                OnStepAfterFilled(entityType, MigrationStep.FillingRelations, startTime, DateTime.Now);

                db4OParallelClient.Close();
                db4OParallelClient.Dispose();
            }, ParallelHandlesCount
                               );
        }
 public static void QueryLocalServer(IObjectServer server)
 {
     using (IObjectContainer client = server.OpenClient())
     {
         ListResult(client.QueryByExample(new Car(null)));
     }
 }
 public Db4oBeekRepository(IObjectServer beekServer)
 {
     server = beekServer;
     client = server.OpenClient();
     genreLock = new object();
     beekLock = new object();
 }
Beispiel #5
0
 private static void StoreData(IObjectServer server)
 {
     using (IObjectContainer container = server.OpenClient())
     {
         container.Store(new Person("Joe"));
     }
 }
Beispiel #6
0
 public static void QueryLocalServer(IObjectServer server)
 {
     using(IObjectContainer client = server.OpenClient())
     {
         ListResult(client.QueryByExample(new Car(null)));
     }
 }
        /// <summary>
        /// Opens the db4o object container.
        /// </summary>
        public void OpenContainer()
        {
            //using (LogGroup logGroup = LogGroup.StartDebug("Opening db4o data container."))
            //{
            LogWriter.Debug("${db4o.OpenContainer:" + Name + "}");

            string fileName = Name;

            string fullName = GetStoreFileName();

            //	LogWriter.Debug("Full file name: " + fullName);

            // Get the server (this activates JIT loading if necessary)
            IObjectServer server = ObjectServer;

            if (!Directory.Exists(Path.GetDirectoryName(fullName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fullName));
            }

            // This info should come after the JIT loading of the object server (to make them show up in the right order in the logs)
            //	LogWriter.Debug("Opening db4o object container: " + Name);

            if (server != null)
            {
                ObjectContainer = server.OpenClient();
            }
            else
            {
                LogWriter.Error("Can't open container because server is not initialized.");
            }
            //}
        }
 private static void StoreData(IObjectServer server)
 {
     using (IObjectContainer container = server.OpenClient())
     {
         container.Store(new Person("Joe"));
     }
 }
 public static void DemonstrateLocalRollback(IObjectServer server)
 {
     using (IObjectContainer client1 = server.OpenClient(),
            client2 = server.OpenClient())
     {
         IObjectSet result = client1.QueryByExample(new Car("BMW"));
         Car        car    = (Car)result.Next();
         car.Pilot = new Pilot("Someone else", 0);
         client1.Store(car);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
         client1.Rollback();
         client1.Ext().Refresh(car, 2);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
     }
 }
 public static void DemonstrateLocalReadCommitted(IObjectServer server)
 {
     using (IObjectContainer client1 = server.OpenClient(),
            client2 = server.OpenClient())
     {
         Pilot      pilot  = new Pilot("David Coulthard", 98);
         IObjectSet result = client1.QueryByExample(new Car("BMW"));
         Car        car    = (Car)result.Next();
         car.Pilot = pilot;
         client1.Store(car);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
         client1.Commit();
         ListResult(client1.QueryByExample(typeof(Car)));
         ListRefreshedResult(client2, client2.QueryByExample(typeof(Car)), 2);
     }
 }
        private IObjectContainer GetStorage()
        {
            if (_db4oServer == null)
            {
                _db4oServer = Db4oFactory.OpenServer(_DBPath, 0);
            }

            return(_db4oServer.OpenClient());
        }
 public static void AccessLocalServer()
 {
     using (IObjectServer server = Db4oClientServer.OpenServer(YapFileName, 0))
     {
         using (IObjectContainer client = server.OpenClient())
         {
             // Do something with this client, or open more clients
         }
     }
 }
 public IObjectContainer GetClient()
 {
     lock (this) {
         if (db4oServer == null)
         {
             throw new InvalidOperationException("Server is not running.");
         }
         return(db4oServer.OpenClient());
     }
 }
Beispiel #14
0
 public Db4oUserRepository(string db4oFilePath)
 {
     FileInfo file = new FileInfo(db4oFilePath);
     if (file.Directory != null && !file.Directory.Exists)
     {
         file.Directory.Create();
     }
     server = Db4oClientServer.OpenServer(db4oFilePath, 0);
     client = server.OpenClient();
     userLock = new object();
 }
Beispiel #15
0
 private void StoreTestData(IObjectServer server)
 {
     using (var db = server.OpenClient())
     {
         foreach (var person in GenerateTestData())
         {
             db.Store(person);
         }
         db.Commit();
     }
 }
Beispiel #16
0
 public void Open(string fname, bool clientServer)
 {
     if (clientServer)
     {
         _server = Db4oClientServer.OpenServer(fname, 0);
         _container = _server.OpenClient();
     }
     else
     {
         _container = Db4oFactory.OpenFile(fname);
     }
 }
Beispiel #17
0
 public void Open(string fname, bool clientServer)
 {
     if (clientServer)
     {
         _server    = Db4oClientServer.OpenServer(fname, 0);
         _container = _server.OpenClient();
     }
     else
     {
         _container = Db4oFactory.OpenFile(fname);
     }
 }
Beispiel #18
0
        /// <summary>
        /// 开启一个客户端实例
        /// </summary>
        /// <returns>客户端实例</returns>
        public IObjectContainer OpenClient()
        {
Begin:
            try
            {
                return(_db4OServer.OpenClient());
            }
            catch
            {
                OpenServer();
                goto Begin;
            }
        }
Beispiel #19
0
 private static void EmbeddedClient()
 {
     CleanUp();
     // #example: Embedded client
     using (IObjectServer server = Db4oClientServer.OpenServer(DatabaseFileName, 0))
     {
         // open the db4o-embedded client. For example at the beginning for a web-request
         using (IObjectContainer container = server.OpenClient())
         {
             // do the operations on the session-container
             container.Store(new Person("Joe"));
         }
     }
     // #end example
 }
Beispiel #20
0
        private Db4oBeekRepository(string db4oFilePath)
        {
            db4oFilePath = EnsureDb4OFilePath(db4oFilePath);
            lock (servers)
            {
                if (!servers.ContainsKey(db4oFilePath))
                {
                    server = Db4oClientServer.OpenServer(db4oFilePath, 0);
                    servers.Add(db4oFilePath, server);
                }
            }

            server = servers[db4oFilePath];
            client = server.OpenClient();
            genreLock = new object();
            beekLock = new object();
        }
    //private static IConfiguration _config = Db4oFactory.NewConfiguration();

    public static void WithContainer(Action <IObjectContainer> action)
    {
        string _dbfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "db4o_linq");

        IObjectServer server = Db4oFactory.OpenServer(_dbfile, 0);

        try
        {
            using (var container = server.OpenClient())
            {
                action(container);
            }
        }
        finally
        {
            server.Close();
        }
    }
Beispiel #22
0
 private OperationResult <bool> Queries()
 {
     using (var db = testDB.OpenClient())
     {
         for (var i = 0; i < QueryRuns; i++)
         {
             try
             {
                 QueriesToRun(db, i);
             }
             catch (Exception e)
             {
                 return(OperationResult.Failure <bool>(e));
             }
         }
         return(OperationResult.Success(true));
     }
 }
Beispiel #23
0
        public static IObjectContainer conectar()
        {
            if (servidor != null)
                servidor.Close();
            IConfiguration config = Db4oFactory.NewConfiguration();
            new TransparentActivationSupport().Prepare(config);
            config.LockDatabaseFile(false);
            config.DetectSchemaChanges(true);
            servidor = Db4oFactory.OpenServer(config, System.Web.HttpContext.Current.Server.MapPath("..\\bdoo\\financas.db4o"), 0);
            //servidor.Ext().Configure().ActivationDepth(2);
            db = servidor.OpenClient();
            db.Ext().Configure().ObjectClass(typeof(Usuario)).CascadeOnUpdate(true);
            db.Ext().Configure().ObjectClass(typeof(Conta)).CascadeOnUpdate(true);
            db.Ext().Configure().ObjectClass(typeof(Categoria)).CascadeOnUpdate(true);
            //db.Ext().Configure().ObjectClass(typeof(Lancamento)).ObjectField("Imagem").CascadeOnActivate(false);
            //db.Ext().Configure().ObjectClass(typeof(Lancamento)).ObjectField("Comprovante").CascadeOnActivate(false);

            return db;
        }
Beispiel #24
0
        public void Setup()
        {
            if (File.Exists(_databasePath))
            {
                File.Delete(_databasePath);
            }

            //Configure Db4o to cascade updates on Order and Customer entities. (Since they are our Aggregate Roots)
            var configuration = Db4oFactory.Configure();

            configuration.ObjectClass(typeof(Order)).CascadeOnUpdate(true);
            configuration.ObjectClass(typeof(Customer)).CascadeOnDelete(true);

            _db4oServer = Db4oFactory.OpenServer(_databasePath, 0);
            Db4oUnitOfWorkFactory.SetContainerProvider(() => _db4oServer.OpenClient());
            _mockLocator = MockRepository.GenerateMock <IServiceLocator>();
            _mockLocator.Expect(x => x.GetInstance <IUnitOfWorkFactory>())
            .Return(new Db4oUnitOfWorkFactory())
            .Repeat.Any();
            ServiceLocator.SetLocatorProvider(() => _mockLocator);
        }
Beispiel #25
0
 static EventHandler<CancellableObjectEventArgs> IncrementIds(IObjectServer server, IObjectContainer container)
 {
     // mostly taken from Tuna Toksoz' excellent article at http://tunatoksoz.com/post/Id-Generation-for-db4o.aspx
      return (sender, args) =>
            {
               var entity = args.Object as Entity;
               if (entity != null)
               {
                  var set = container.QueryByExample(new IncrementTypeValuePair {Type = args.Object.GetType()});
                  IncrementTypeValuePair pair;
                  if (set.Count == 0)
                     pair = new IncrementTypeValuePair {Type = args.Object.GetType()};
                  else
                     pair = (IncrementTypeValuePair) set[0];
                  entity.Id = ++pair.Value;
                  var client = server.OpenClient();
                  client.Store(pair);
                  client.Commit();
               }
            };
 }
Beispiel #26
0
        public void Nested_UnitOfWork_With_Different_Transaction_Compatibility_Works()
        {
            var changedShipDate  = DateTime.Now.AddDays(1);
            var changedOrderDate = DateTime.Now.AddDays(2);

            using (var testData = new Db4oTestDataGenerator(_db4oServer.OpenClient()))
            {
                testData.Batch(actions =>
                               actions.CreateOrderForCustomer(actions.CreateCustomer()));

                int orderId;
                using (new UnitOfWorkScope())
                {
                    var ordersRepository = new Db4oRepository <Order>();
                    orderId = ordersRepository.Select(x => x.OrderID).First();
                }

                Assert.NotNull(orderId);
                using (new UnitOfWorkScope())
                {
                    var outerRepository = new Db4oRepository <Order>();
                    var outerOrder      = outerRepository.Where(x => x.OrderID == orderId).First();
                    outerOrder.OrderDate = changedOrderDate;

                    using (var innerScope = new UnitOfWorkScope(UnitOfWorkScopeTransactionOptions.CreateNew))
                    {
                        var innerRepository = new Db4oRepository <Order>();
                        var innerOrder      = innerRepository.Where(x => x.OrderID == orderId).First();
                        innerOrder.ShipDate = changedShipDate;
                        innerScope.Commit();
                    }
                }

                using (new UnitOfWorkScope())
                {
                    var ordersRepository = new Db4oRepository <Order>();
                    var order            = ordersRepository.First();
                    Assert.That(order.OrderDate, Is.Not.EqualTo(changedOrderDate));
                    Assert.That(order.ShipDate, Is.Not.EqualTo(changedShipDate));
                }
            }
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //LinqIndex.Run();
            //return;

            IObjectContainer db;
            IObjectServer    server = null;

            bool   multiple_client = false;
            string dbpath          = "/tmp/temp.n.db";

            File.Delete(dbpath);

            if (!multiple_client)
            {
                db = Db4oEmbedded.OpenFile(dbpath);
            }
            else
            {
                var config = Db4oClientServer.NewServerConfiguration();
                config.Common.Diagnostic.AddListener(new DiagnosticToConsole());
                //Wait before close()
                config.TimeoutServerSocket = 1000 * 10;
                server = Db4oClientServer.OpenServer(config, dbpath, 0);
                IObjectContainer client = server.OpenClient();
                db = client;
            }
            try
            {
                // Store a few Person objects

                db.Store(new Person("Petra"));

                db.Store(new Person("Gallad"));

                // Retrieve the Person
                Person p;
                {
                    Console.WriteLine("001");
                    var results = db.Query <Person>(x => x.Name == "Petra");
                    p = results.First();
                    Console.WriteLine(p.Name);
                }

                {
                    Console.WriteLine("002");
                    var result2 = from Person tp in db
                                  where tp.Name == "Petra"
                                  select tp;
                    p = result2.First();
                    Console.WriteLine(p.Name);
                }

                {
                    Console.WriteLine("003");
                    var result2 = from Person tp in db
                                  where tp.Name.StartsWith("Petr")
                                  select tp;
                    p = result2.First();
                    Console.WriteLine(p.Name);
                }

                {
                    Console.WriteLine("004");
                    var result2 = from Person tp in db
                                  where tp.Age == 9 && tp.Name == "Petra"
                                  select tp;
                    p = result2.First();
                    Console.WriteLine(p.Name);
                }
                {
                    Console.WriteLine("005");
                    var uid = db.Ext().GetObjectInfo(p).GetInternalID();
                    p = (Person)db.Ext().GetByID(uid);
                    Console.WriteLine(p.Name);
                }
                p.Name = "Peter";
                db.Store(p);


                // Delete the person
                db.Delete(p);

                // Don't forget to commit!
                db.Commit();
                Console.WriteLine("Commited " + db.Query <Person>().Count(x => x.Age >= 0));
            }

            catch (Exception ex)
            {
                db.Rollback();
                Console.WriteLine(ex.ToString());
                throw ex;
            }

            finally
            {
                // Close the db cleanly
                db.Close();

                //Environment.Exit(0);, just Exit() will faster
                server?.Close();
            }

            Console.WriteLine("End.");
        }
Beispiel #28
0
 public void Connect(string dbPath)
 {
     _server = Db4oFactory.OpenServer(dbPath, 0);
     DB = _server.OpenClient();
 }
Beispiel #29
0
 public Db4oUserRepository(IObjectServer server)
 {
     this.server = server;
     client = server.OpenClient();
     userLock = new object();
 }
        public void Setup()
        {
            if (File.Exists(_databasePath))
                File.Delete(_databasePath);

            //Configure Db4o to cascade updates on Order and Customer entities. (Since they are our Aggregate Roots)
            var configuration = Db4oFactory.Configure();
            configuration.ObjectClass(typeof (Order)).CascadeOnUpdate(true);
            configuration.ObjectClass(typeof (Customer)).CascadeOnDelete(true);

            _db4oServer = Db4oFactory.OpenServer(_databasePath, 0);
            Db4oUnitOfWorkFactory.SetContainerProvider(() => _db4oServer.OpenClient());
            _mockLocator = MockRepository.GenerateMock<IServiceLocator>();
            _mockLocator.Expect(x => x.GetInstance<IUnitOfWorkFactory>())
                .Return(new Db4oUnitOfWorkFactory())
                .Repeat.Any();
            ServiceLocator.SetLocatorProvider(() => _mockLocator);
        }
Beispiel #31
0
 public static void DemonstrateLocalReadCommitted(IObjectServer server)
 {
     using(IObjectContainer client1 =server.OpenClient(),
         client2 =server.OpenClient())
     {
         Pilot pilot = new Pilot("David Coulthard", 98);
         IObjectSet result = client1.QueryByExample(new Car("BMW"));
         Car car = (Car)result.Next();
         car.Pilot = pilot;
         client1.Store(car);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
         client1.Commit();
         ListResult(client1.QueryByExample(typeof(Car)));			
         ListRefreshedResult(client2, client2.QueryByExample(typeof(Car)), 2);
     }
 }
Beispiel #32
0
 public static void DemonstrateLocalRollback(IObjectServer server)
 {
     using (IObjectContainer client1 = server.OpenClient(),
         client2 = server.OpenClient())
     {
         IObjectSet result = client1.QueryByExample(new Car("BMW"));
         Car car = (Car) result.Next();
         car.Pilot = new Pilot("Someone else", 0);
         client1.Store(car);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
         client1.Rollback();
         client1.Ext().Refresh(car, 2);
         ListResult(client1.QueryByExample(new Car(null)));
         ListResult(client2.QueryByExample(new Car(null)));
     }
 }
Beispiel #33
0
 public Db4ORepository(IObjectServer server)
 {
     _database = server.OpenClient();
 }
Beispiel #34
0
 public virtual IObjectContainer OpenClient()
 {
     return(_server.OpenClient());
 }
Beispiel #35
0
 /// <summary>
 /// Retrieve an IObjectContainer which is the key into the database
 /// </summary>
 /// <returns></returns>
 public IObjectContainer GetClient()
 {
     _log.Debug("Opening connection to DB");
     return(_theDatabase.OpenClient());
 }