Ejemplo n.º 1
0
 public virtual Lite <DisconnectedImportEntity> BeginImportDatabase(DisconnectedMachineEntity machine, Stream?file = null)
 {
     Lite <DisconnectedImportEntity> import = new DisconnectedImportEntity
     {
         Machine = machine.ToLite(),
         Copies  = uploadTables.Select(t => new DisconnectedImportTableEmbedded
         {
             Type = t.Type.ToTypeEntity().ToLite(),
             DisableForeignKeys = t.Strategy.DisableForeignKeys !.Value,
         }).ToMList()
Ejemplo n.º 2
0
        public virtual Lite <DisconnectedExportEntity> BeginExportDatabase(DisconnectedMachineEntity machine)
        {
            Lite <DisconnectedExportEntity> export = new DisconnectedExportEntity
            {
                Machine = machine.ToLite(),
                Copies  = downloadTables.Select(t => new DisconnectedExportTableEmbedded
                {
                    Type = t.Type.ToTypeEntity().ToLite()
                }).ToMList()
            }.Save().ToLite();

            var cancelationSource = new CancellationTokenSource();

            var user = UserHolder.Current;

            var token = cancelationSource.Token;

            var task = Task.Factory.StartNew(() =>
            {
                using (UserHolder.UserSession(user))
                {
                    OnStartExporting(machine);
                    DisconnectedMachineEntity.Current = machine.ToLite();

                    try
                    {
                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.Lock, s => l).Execute()))
                        {
                            foreach (var tuple in downloadTables)
                            {
                                token.ThrowIfCancellationRequested();

                                if (tuple.Strategy.Upload == Upload.Subset)
                                {
                                    miUnsafeLock.MakeGenericMethod(tuple.Type).Invoke(this, new object[] { machine.ToLite(), tuple.Strategy, export });
                                }
                            }
                        }

                        string connectionString;
                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.CreateDatabase, s => l).Execute()))
                            connectionString = CreateDatabase(machine);

                        var newDatabase = new SqlServerConnector(connectionString, Schema.Current, ((SqlServerConnector)Connector.Current).Version);


                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.CreateSchema, s => l).Execute()))
                            using (Connector.Override(newDatabase))
                                using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                    AvoidDatabaseName = true
                                }))
                                {
                                    Administrator.TotalGeneration();
                                }

                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.DisableForeignKeys, s => l).Execute()))
                            using (Connector.Override(newDatabase))
                                using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                    AvoidDatabaseName = true
                                }))
                                {
                                    foreach (var tuple in downloadTables.Where(t => !t.Type.IsEnumEntity()))
                                    {
                                        token.ThrowIfCancellationRequested();

                                        DisableForeignKeys(tuple.Table);
                                    }
                                }

                        var isPostgres = Schema.Current.Settings.IsPostgres;
                        DatabaseName newDatabaseName = new DatabaseName(null, newDatabase.DatabaseName(), isPostgres);

                        foreach (var tuple in downloadTables)
                        {
                            token.ThrowIfCancellationRequested();
                            int ms = 0;
                            using (token.MeasureTime(l => ms = l))
                            {
                                tuple.Strategy.Exporter !.Export(tuple.Table, tuple.Strategy, newDatabaseName, machine);
                            }

                            export.MListElementsLite(_ => _.Copies).Where(c => c.Element.Type.Is(tuple.Type.ToTypeEntity())).UnsafeUpdateMList()
                            .Set(mle => mle.Element.CopyTable, mle => ms)
                            .Execute();
                        }

                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.EnableForeignKeys, s => l).Execute()))
                            foreach (var tuple in downloadTables.Where(t => !t.Type.IsEnumEntity()))
                            {
                                token.ThrowIfCancellationRequested();

                                EnableForeignKeys(tuple.Table);
                            }

                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.ReseedIds, s => l).Execute()))
                        {
                            var tablesToUpload = Schema.Current.Tables.Values.Where(t => DisconnectedLogic.GetStrategy(t.Type).Upload != Upload.None)
                                                 .SelectMany(t => t.TablesMList().Cast <ITable>().And(t)).Where(t => t.PrimaryKey.Identity).ToList();

                            var maxIdDictionary = tablesToUpload.ToDictionary(t => t,
                                                                              t => DisconnectedTools.MaxIdInRange(t, machine.SeedMin, machine.SeedMax));

                            using (Connector.Override(newDatabase))
                                using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                    AvoidDatabaseName = true
                                }))
                                {
                                    foreach (var table in tablesToUpload)
                                    {
                                        token.ThrowIfCancellationRequested();

                                        long?max = maxIdDictionary.GetOrThrow(table);

                                        DisconnectedTools.SetNextId(table, (max + 1) ?? machine.SeedMin);
                                    }
                                }
                        }

                        CopyExport(export, newDatabase);

                        machine.InDB().UnsafeUpdate().Set(s => s.State, s => DisconnectedMachineState.Disconnected).Execute();
                        using (SqlServerConnector.Override(newDatabase))
                            using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                AvoidDatabaseName = true
                            }))
                                machine.InDB().UnsafeUpdate().Set(s => s.State, s => DisconnectedMachineState.Disconnected).Execute();

                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.BackupDatabase, s => l).Execute()))
                            BackupDatabase(machine, export, newDatabase);

                        using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.DropDatabase, s => l).Execute()))
                            DropDatabase(newDatabase);

                        token.ThrowIfCancellationRequested();

                        export.InDB().UnsafeUpdate()
                        .Set(s => s.State, s => DisconnectedExportState.Completed)
                        .Set(s => s.Total, s => s.CalculateTotal())
                        .Execute();
                    }
                    catch (Exception e)
                    {
                        var ex = e.LogException();

                        export.InDB().UnsafeUpdate()
                        .Set(s => s.Exception, s => ex.ToLite())
                        .Set(s => s.State, s => DisconnectedExportState.Error)
                        .Execute();

                        OnExportingError(machine, export, e);
                    }
                    finally
                    {
                        runningExports.Remove(export);
                        DisconnectedMachineEntity.Current = null;

                        OnEndExporting();
                    }
                }
            });


            runningExports.Add(export, new RunningExports(task, cancelationSource));

            return(export);
        }
Ejemplo n.º 3
0
        public virtual Lite <DisconnectedImportEntity> BeginImportDatabase(DisconnectedMachineEntity machine, Stream file = null)
        {
            Lite <DisconnectedImportEntity> import = new DisconnectedImportEntity
            {
                Machine = machine.ToLite(),
                Copies  = uploadTables.Select(t => new DisconnectedImportTableEmbedded
                {
                    Type = t.Type.ToTypeEntity().ToLite(),
                    DisableForeignKeys = t.Strategy.DisableForeignKeys.Value,
                }).ToMList()
            }.Save().ToLite();

            if (file != null)
            {
                using (FileStream fs = File.OpenWrite(BackupNetworkFileName(machine, import)))
                {
                    file.CopyTo(fs);
                    file.Close();
                }
            }

            var threadContext = Statics.ExportThreadContext();

            var cancelationSource = new CancellationTokenSource();

            var user = UserEntity.Current;

            var token = cancelationSource.Token;

            var task = Task.Factory.StartNew(() =>
            {
                lock (SyncLock)
                    using (UserHolder.UserSession(user))
                    {
                        OnStartImporting(machine);

                        DisconnectedMachineEntity.Current = machine.ToLite();

                        try
                        {
                            if (file != null)
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.RestoreDatabase, s => l).Execute()))
                                {
                                    DropDatabaseIfExists(machine);
                                    RestoreDatabase(machine, import);
                                }
                            }

                            string connectionString = GetImportConnectionString(machine);

                            var newDatabase = new SqlConnector(connectionString, Schema.Current, DynamicQueryManager.Current, ((SqlConnector)Connector.Current).Version);

                            using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.SynchronizeSchema, s => l).Execute()))
                                using (Connector.Override(newDatabase))
                                    using (ObjectName.OverrideOptions(new ObjectNameOptions {
                                        AvoidDatabaseName = true
                                    }))
                                        using (ExecutionMode.DisableCache())
                                        {
                                            var script = Administrator.TotalSynchronizeScript(interactive: false, schemaOnly: true);

                                            if (script != null)
                                            {
                                                string fileName = BackupNetworkFileName(machine, import) + ".sql";
                                                script.Save(fileName);
                                                throw new InvalidOperationException("The schema has changed since the last export. A schema sync script has been saved on: {0}".FormatWith(fileName));
                                            }
                                        }

                            try
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DisableForeignKeys, s => l).Execute()))
                                    foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys.Value))
                                    {
                                        DisableForeignKeys(item.Table);
                                    }

                                foreach (var tuple in uploadTables)
                                {
                                    ImportResult result = null;
                                    using (token.MeasureTime(l =>
                                    {
                                        if (result != null)
                                        {
                                            import.MListElementsLite(_ => _.Copies).Where(mle => mle.Element.Type.RefersTo(tuple.Type.ToTypeEntity())).UnsafeUpdateMList()
                                            .Set(mle => mle.Element.CopyTable, mle => l)
                                            .Set(mle => mle.Element.DisableForeignKeys, mle => tuple.Strategy.DisableForeignKeys.Value)
                                            .Set(mle => mle.Element.InsertedRows, mle => result.Inserted)
                                            .Set(mle => mle.Element.UpdatedRows, mle => result.Updated)
                                            .Execute();
                                        }
                                    }))
                                    {
                                        result = tuple.Strategy.Importer.Import(machine, tuple.Table, tuple.Strategy, newDatabase);
                                    }
                                }

                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.Unlock, s => l).Execute()))
                                    UnlockTables(machine.ToLite());
                            }
                            finally
                            {
                                using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.EnableForeignKeys, s => l).Execute()))
                                    foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys.Value))
                                    {
                                        EnableForeignKeys(item.Table);
                                    }
                            }

                            using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DropDatabase, s => l).Execute()))
                                DropDatabase(newDatabase);

                            token.ThrowIfCancellationRequested();

                            import.InDB().UnsafeUpdate()
                            .Set(s => s.State, s => DisconnectedImportState.Completed)
                            .Set(s => s.Total, s => s.CalculateTotal())
                            .Execute();

                            machine.InDB().UnsafeUpdate()
                            .Set(m => m.State, m => file == null ? DisconnectedMachineState.Fixed : DisconnectedMachineState.Connected)
                            .Execute();
                        }
                        catch (Exception e)
                        {
                            var ex = e.LogException();

                            import.InDB().UnsafeUpdate()
                            .Set(m => m.Exception, m => ex.ToLite())
                            .Set(m => m.State, m => DisconnectedImportState.Error)
                            .Execute();

                            machine.InDB().UnsafeUpdate()
                            .Set(m => m.State, m => DisconnectedMachineState.Faulted)
                            .Execute();

                            OnImportingError(machine, import, e);
                        }
                        finally
                        {
                            runningImports.Remove(import);

                            DisconnectedMachineEntity.Current = null;

                            OnEndImporting();
                        }
                    }
            });


            runningImports.Add(import, new RunningImports {
                Task = task, CancelationSource = cancelationSource
            });

            return(import);
        }