public void GenerateCode() { if (_generatorProviders.Count() == 0) { Log.Warn("No BaseDataObjectGenerators found. Exiting the Generator."); return; } using (Log.InfoTraceMethodCall("GenerateCode", "Generating DAL-classes")) { var workingPath = _config.Server.CodeGenWorkingPath; if (String.IsNullOrEmpty(workingPath)) { throw new ConfigurationException("CodeGenWorkingPath is not defined in the current configuration file."); } if (!Directory.Exists(workingPath)) { Log.InfoFormat("Creating destination directory: [{0}]", workingPath); Directory.CreateDirectory(workingPath); } GenerateTo(workingPath); CompileCodeOnStaThread(workingPath); PublishOutput(); Log.Info("Finished generating Code"); } }
protected override void SetUp(IContainer container) { base.SetUp(container); ResetDatabase(container); AutofacServiceHostFactory.Container = container; var config = container.Resolve <ZetboxConfig>(); using (Log.InfoTraceMethodCall("Starting server domain")) { manager = container.Resolve <IZetboxAppDomain>(); manager.Start(config); } }
/// <summary> /// Starts the WCF Server in the background. If the server hasn't /// started successfully within 40 seconds, it is aborted and an /// <see cref="InvalidOperationException"/> is thrown. /// </summary> /// <param name="config">the loaded configuration for the Server</param> public void Start(ZetboxConfig config) { if (config == null) { throw new ArgumentNullException("config"); } if (config.AdditionalCommandlineOptions.ContainsKey(ServerModule.NoWcfKey)) { Log.Info("Not starting embedded WCF Server. As requested by -nowcf."); } else { using (Log.InfoTraceMethodCall("Starting Server")) { serviceThread = new Thread(new ThreadStart(this.RunWCFServer)); serviceThread.Start(); if (!serverStarted.WaitOne(40 * 1000, false)) { throw new InvalidOperationException("Server did not start within 40 sec."); } } } }
public void ResetDatabase() { using (Log.InfoTraceMethodCall("ResetDatabase")) { var connectionString = config.Server.GetConnectionString(Zetbox.API.Helper.ZetboxConnectionStringKey); Assert.That(connectionString.ConnectionString, Is.StringContaining("_test"), "test databases should be marked with '_test' in the connection string"); try { Log.Info("Restoring Database"); var cb = new SqlConnectionStringBuilder(connectionString.ConnectionString); cb.InitialCatalog = "master"; Log.InfoFormat("executing on database [{0}]", cb.ToString()); ExecuteScript(cb.ToString(), "Zetbox.Tests.Utilities.MsSql.BackupRestoreTestDatabase.sql"); Log.Info("Done restoring Database"); // After recreating the database, all connection pools should be cleard SqlConnection.ClearAllPools(); } catch (Exception ex) { Log.Error("Error while restoring database", ex); throw; } Log.InfoFormat("Current Directory=[{0}]", Environment.CurrentDirectory); Log.InfoFormat("Using config from [{0}]", config.ConfigFilePath); } }
public void DropAllObjects() { using (Log.InfoTraceMethodCall("Dropping all database objects")) { _provider.DropAllObjects(); } }
public void SetUpTestFixture() { using (Log.InfoTraceMethodCall("EarlySetup")) { EarlySetup(); } using (Log.InfoTraceMethodCall("Starting up")) { var config = ZetboxConfig.FromFile(null, GetConfigFile()); AssemblyLoader.Bootstrap(AppDomain.CurrentDomain, config); ContainerBuilder builder; switch (GetHostType()) { case HostType.Server: Log.Info("Adding Server Modules"); builder = Zetbox.API.Utils.AutoFacBuilder.CreateContainerBuilder(config, config.Server.Modules); break; case HostType.Client: Log.Info("Adding Client Modules"); builder = Zetbox.API.Utils.AutoFacBuilder.CreateContainerBuilder(config, config.Client.Modules); break; case HostType.None: Log.Info("Adding no Modules"); builder = Zetbox.API.Utils.AutoFacBuilder.CreateContainerBuilder(config); break; default: throw new InvalidOperationException("GetHostType() returned an unknown type"); } // TODO: totally replace this with test mocks? Log.Info("Adding Interface Module"); builder.RegisterModule <Zetbox.Objects.InterfaceModule>(); builder.RegisterInstance <TypeMapAssembly>(new TypeMapAssembly(this.GetType().Assembly)); SetupBuilder(builder); container = builder.Build(); SetUp(container); } }
public virtual void Generate(Zetbox.API.IZetboxContext ctx, string basePath) { using (Log.InfoTraceMethodCall("Generate", "Generating " + this.BaseName)) { InitCodeBasePath(basePath); Directory.CreateDirectory(CodeBasePath); DeleteOldFiles(); SaveKeyFile(); var generatedFileNames = new List <string>(); generatedFileNames.AddRange(Generate_Objects(ctx)); Log.Info(" Assemblyinfo"); generatedFileNames.Add(Generate_AssemblyInfo(ctx)); Log.Info(" Other Files"); generatedFileNames.AddRange(Generate_Other(ctx)); Log.Info(" Project File"); Generate_ProjectFile(ctx, ProjectGuid, generatedFileNames, _schemaProviders); } }
public void AnalyzeDatabase(string connectionName, TextWriter output) { using (Log.InfoTraceMethodCall("AnalyzeDatabase", connectionName)) using (var subContainer = container.BeginLifetimeScope()) { var config = subContainer.Resolve <ZetboxConfig>(); var connectionString = config.Server.GetConnectionString(connectionName); var schemaProvider = subContainer.ResolveNamed <ISchemaProvider>(connectionString.SchemaProvider); schemaProvider.Open(connectionString.ConnectionString); output.WriteLine("# Tables"); foreach (var table in schemaProvider.GetTableNames().OrderBy(t => t.Name)) { output.WriteLine(" * {0}", table); } output.WriteLine("# Views"); foreach (var view in schemaProvider.GetViewNames().OrderBy(v => v.Name)) { output.WriteLine(" * {0}", view); foreach (var line in schemaProvider.GetViewDefinition(view).Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { output.WriteLine(" > {0}", line); } output.WriteLine(); } output.WriteLine("# Procedures"); foreach (var proc in schemaProvider.GetProcedureNames().OrderBy(p => p.Name)) { output.WriteLine(" * {0}", proc); foreach (var line in schemaProvider.GetProcedureDefinition(proc).Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { output.WriteLine(" > {0}", line); } output.WriteLine(); } } }
public static void Deploy(IZetboxContext ctx, params IPackageProvider[] providers) { if (ctx == null) { throw new ArgumentNullException("ctx"); } if (providers == null) { throw new ArgumentNullException("providers"); } using (Log.InfoTraceMethodCall("Deploy")) { Log.InfoFormat("Starting Deployment from {0}", string.Join(", ", providers.Select(p => p.ToString()).ToArray())); try { // TODO: Das muss ich z.Z. machen, weil die erste Query eine Entity Query ist und noch nix geladen wurde.... var testObj = ctx.GetQuery <Zetbox.App.Base.ObjectClass>().FirstOrDefault(); Debug.WriteLine(testObj != null ? testObj.ToString() : String.Empty); } catch { // Ignore } Dictionary <Guid, IPersistenceObject> currentObjects = new Dictionary <Guid, IPersistenceObject>(); Log.Info("Loading namespaces"); var names = providers.SelectMany(p => LoadModuleNames(p)).Distinct().ToList(); if (names.Count == 0) { throw new InvalidOperationException("No modules found in import file"); } foreach (var name in names) { Log.InfoFormat("Prefetching objects for {0}", name); var module = ctx.GetQuery <Zetbox.App.Base.Module>().FirstOrDefault(m => m.Name == name); if (module != null) { foreach (var obj in PackagingHelper.GetMetaObjects(ctx, module)) { currentObjects[((Zetbox.App.Base.IExportable)obj).ExportGuid] = obj; } } else { Log.InfoFormat("Found new Module '{0}' in XML", name); } } providers.ForEach(p => p.RewindData()); Dictionary <Guid, IPersistenceObject> importedObjects = new Dictionary <Guid, IPersistenceObject>(); Log.Info("Loading"); foreach (var p in providers) { var reader = p.Reader; // Find Root Element while (reader.Read() && reader.NodeType != XmlNodeType.Element && reader.LocalName != "ZetboxPackaging" && reader.NamespaceURI != "http://dasz.at/Zetbox") { ; } // Read content while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) { continue; } var obj = ImportElement(ctx, currentObjects, p); if (obj == null) { throw new InvalidOperationException("Invalid import format: ImportElement returned NULL"); } importedObjects[((IExportableInternal)obj).ExportGuid] = obj; } } Log.Info("Reloading References"); foreach (var obj in importedObjects.Values) { obj.ReloadReferences(); } var objectsToDelete = currentObjects.Where(p => !importedObjects.ContainsKey(p.Key)); Log.InfoFormat("Deleting {0} objects marked for deletion", objectsToDelete.Count()); foreach (var pairToDelete in objectsToDelete) { ctx.Delete(pairToDelete.Value); } Log.Info("Deployment finished"); } }
public static void UpdateFromSourceSchema(Zetbox.App.SchemaMigration.MigrationProject obj) { foreach (var s in obj.StagingDatabases) { using (Log.InfoTraceMethodCall("UpdateFromSourceSchema", s.Description)) { var connectionString = _cfg.Server.GetConnectionString(s.ConnectionStringKey); if (string.IsNullOrEmpty(connectionString.ConnectionString)) { throw new InvalidOperationException("Source ConnectionString is empty"); } if (string.IsNullOrEmpty(connectionString.SchemaProvider)) { throw new InvalidOperationException("Source Provider is empty"); } ISchemaProvider src = _scope.ResolveNamed <ISchemaProvider>(connectionString.SchemaProvider); src.Open(connectionString.ConnectionString); var destTbls = s.SourceTables .ToDictionary(k => k.Name); // foreach table in src // TODO: And views!! foreach (var tbl in src.GetTableNames().ToList().Union(src.GetViewNames().ToList())) { if (tbl.Schema != s.Schema) { continue; } Log.InfoFormat("reading table {0}", tbl); SourceTable destTbl; if (!destTbls.ContainsKey(tbl.Name)) { destTbl = obj.Context.Create <SourceTable>(); destTbl.Name = tbl.Name; s.SourceTables.Add(destTbl); } else { destTbl = destTbls[tbl.Name]; } var cols = src.GetTableColumns(tbl); var destCols = obj.Context.GetQuery <SourceColumn>() .Where(i => i.SourceTable == destTbl) .ToDictionary(k => k.Name); foreach (var col in cols) { SourceColumn destCol; if (!destCols.ContainsKey(col.Name)) { destCol = obj.Context.Create <SourceColumn>(); destCol.Name = col.Name; destTbl.SourceColumn.Add(destCol); } else { destCol = destCols[col.Name]; } destCol.DbType = (ColumnType)col.Type; destCol.IsNullable = col.IsNullable; destCol.Size = col.Size; } } } } // TODO: For now, submit changes // Later, implement InvokeOnServer correctly obj.Context.SubmitChanges(); }
public void ResetDatabase() { using (Log.InfoTraceMethodCall("ResetDatabase")) { var connectionString = config.Server.GetConnectionString(Zetbox.API.Helper.ZetboxConnectionStringKey); Assert.That(connectionString.ConnectionString, Is.StringContaining("_test"), "test databases should be marked with '_test' in the connection string"); Log.InfoFormat("Current Directory=[{0}]", Environment.CurrentDirectory); Log.InfoFormat("Using config from [{0}]", config.ConfigFilePath); try { Log.Info("Restoring Database"); var cb = new NpgsqlConnectionStringBuilder(connectionString.ConnectionString); var srcDB = cb.Database.Substring(0, cb.Database.Length - "_test".Length); var destDB = cb.Database; var userCmdString = "--username=sa --no-password"; var dumpFile = tmpService.CreateWithExtension(".zetbox.backup"); try { var exitCode = RunPgUtil("pg_dump", String.Format("--format c {0} --file={1} {2}", userCmdString, dumpFile, srcDB)); if (exitCode != 0) { throw new ApplicationException(String.Format("Failed to dump database (exit={0}), maybe you need to put your password into AppData\\Roaming\\postgresql\\pgpass.conf", exitCode)); } var admin = new NpgsqlConnectionStringBuilder(connectionString.ConnectionString); var dbName = admin.Database; using (Log.InfoTraceMethodCall("DropCreateDatabase", string.Format("Recreating database {0}", dbName))) { admin.Database = "postgres"; // use "default" database to connect, when trying to drop "dbName" schemaManager.Open(admin.ConnectionString); if (schemaManager.CheckDatabaseExists(dbName)) { schemaManager.DropDatabase(dbName); } schemaManager.CreateDatabase(dbName); } exitCode = RunPgUtil("pg_restore", String.Format("--format c {0} --dbname={2} {1}", userCmdString, dumpFile, destDB)); if (exitCode != 0) { throw new ApplicationException(String.Format("Failed to restore database (exit={0})", exitCode)); } schemaManager.RefreshDbStats(); } finally { // cleanup File.Delete(dumpFile); // After recreating the database, all connection pools should be cleard NpgsqlConnection.ClearAllPools(); } } catch (ApplicationException) { throw; } catch (Exception ex) { Log.Error("Error while restoring database", ex); throw; } } }