public Exporter(PathManager mgr, TreeNode<IDataPath> pt, Configuration cfg) { this.mgr = mgr; this.cfg = cfg; this.xml = new XmlDbFile { XmlDbFolder = cfg.XmlDbFolder }; this.fileName = cfg.OutputFile; if (pt.Item is Locator) { this.tname = mgr.GetPathFrom<TableName>(pt); this.dname = tname.DatabaseName; this.sname = dname.ServerName; } else if (pt.Item is TableName) { this.tname = (TableName)pt.Item; this.dname = tname.DatabaseName; this.sname = dname.ServerName; } else if (pt.Item is DatabaseName) { this.tname = null; this.dname = (DatabaseName)pt.Item; this.sname = dname.ServerName; } else if (pt.Item is ServerName) { this.tname = null; this.dname = null; this.sname = (ServerName)pt.Item; } }
public static string DatabaseSchemaDifference(CompareSideType sideType, DatabaseName dname1, DatabaseName dname2) { TableName[] names = dname1.GetDependencyTableNames(); StringBuilder builder = new StringBuilder(); foreach (TableName tableName in names) { #if DEBUG Console.WriteLine(tableName.ShortName); #endif try { string sql = TableSchemaDifference(sideType, tableName, new TableName(dname2, tableName.SchemaName, tableName.Name)); builder.Append(sql); #if DEBUG if (sql != string.Empty) Console.WriteLine(sql); #endif } catch (Exception ex) { Console.WriteLine("error:" + ex.Message); } } return builder.ToString(); }
public static string Difference(DataProvider from, DataProvider to, string dbNameFrom, string dbNameTo) { DatabaseName dname1 = new DatabaseName(from, dbNameFrom); DatabaseName dname2 = new DatabaseName(to, dbNameTo); string[] names = MetaDatabase.GetTableNames(dname1); StringBuilder builder = new StringBuilder(); foreach (string tableName in names) { TableName tname1 = new TableName(dname1, tableName); TableName tname2 = new TableName(dname2, tableName); string[] primaryKeys = InformationSchema.PrimaryKeySchema(tname1).ToArray<string>(0); if (primaryKeys.Length == 0) continue; if (MetaDatabase.TableExists(tname2)) { builder.Append(TableCompare.Difference(tname1, tname2, tableName, primaryKeys)); } else { builder.Append(TableCompare.Rows(tableName, from)); } builder.AppendLine(); } return builder.ToString(); }
protected virtual void RestoreDatabase(DatabaseName databaseName, string backupFile, string databaseFile, string databaseLogFile) { DisconnectedTools.RestoreDatabase(databaseName, Absolutize(backupFile), Absolutize(databaseFile), Absolutize(databaseLogFile)); }
public bool SetSink(string sink) { if (sink != null) { return SetSource(sink,"destination"); } else node = mgr.current; dname = mgr.GetPathFrom<DatabaseName>(node); if (dname == null) { stdio.ErrorFormat("warning: destination database is unavailable"); return false; } var tname = mgr.GetPathFrom<TableName>(node); if (tname != null) T = new TableName[] { tname }; else T = dname.GetTableNames(); var server = mgr.GetPathFrom<ServerName>(node); side = new Side(server.Provider, dname); return true; }
public MatchedDatabase(DatabaseName databaseName, string namePattern, string[] excludedtables) { this.namePattern = namePattern; this.DatabaseName = databaseName; if(excludedtables != null) this.Excludedtables = excludedtables; }
public SpProc(DatabaseName databaseName, string spName, string spDef) { this.databaseName = databaseName; this.spName = spName; this.spDef = spDef; this.spDefVariable = "_" + spName; }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseConfiguration"/> class with /// the specified name, character set, and collation configuration. /// </summary> /// <param name="name">The name of the database.</param> /// <param name="characterSet">The MySQL character set. If the value is <see langword="null"/>, a provider-specific default value is used.</param> /// <param name="collate">The MySQL collation configuration. If the value is <see langword="null"/>, a provider-specific default value is used.</param> /// <exception cref="ArgumentNullException">If <paramref name="name"/> is <see langword="null"/>.</exception> public DatabaseConfiguration(DatabaseName name, string characterSet, string collate) { if (name == null) throw new ArgumentNullException("name"); _name = name; _characterSet = characterSet; _collate = collate; }
public static void CreateDatabase(DatabaseName databaseName, string databaseFile, string databaseLogFile) { string script = @"CREATE DATABASE {0} ON PRIMARY ( NAME = N'{0}_Data', FILENAME = N'{1}' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB ) LOG ON ( NAME = N'{0}_Log', FILENAME = N'{2}' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )".FormatWith(databaseName, databaseFile, databaseLogFile); Executor.ExecuteNonQuery(script); }
public static DataTable executeQuery(DatabaseName databaseName, String query) { DataTable dataTable = new DataTable(); MySqlConnection mySqlConnection = new MySqlConnection(SQLData.ConnStr(databaseName.ToString())); mySqlConnection.Open(); MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, mySqlConnection); mySqlDataAdapter.Fill(dataTable); mySqlConnection.Close(); return dataTable; }
public string WriteSchema(DatabaseName dname) { var file = getSchemaFilName(dname); using (var writer = NewStreamWriter(file)) { DataTable dt = dname.DatabaseSchema(); dt.WriteXml(writer, XmlWriteMode.WriteSchema); } return file; }
public SpDatabase(DatabaseName databaseName, string path) { this.databaseName = databaseName; this.path = string.Format("{0}\\{1}\\{2}",path, (int)databaseName.Provider, databaseName.Name); if (!Directory.Exists(this.path)) { Directory.CreateDirectory(this.path); } }
public override DatabaseName[] GetDatabaseNames() { List<DatabaseName> dnames = new List<DatabaseName>(); foreach (DataTable table in dbSchema.Tables) { DatabaseName dname = new DatabaseName(provider, table.TableName); dnames.Add(dname); } return dnames.ToArray(); }
public static void DropIfExists(DatabaseName databaseName) { string dropDatabase = @"IF EXISTS(SELECT name FROM sys.databases WHERE name = '{0}') BEGIN ALTER DATABASE {0} SET single_user WITH ROLLBACK IMMEDIATE DROP DATABASE {0} END".FormatWith(databaseName); Executor.ExecuteNonQuery(dropDatabase); }
public override DataTable GetDependencySchema(DatabaseName dname) { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("FK_SCHEMA", typeof(string))); dt.Columns.Add(new DataColumn("FK_Table", typeof(string))); dt.Columns.Add(new DataColumn("PK_SCHEMA", typeof(string))); dt.Columns.Add(new DataColumn("PK_Table", typeof(string))); dt.AcceptChanges(); return dt; }
public void SetIamPolicy() { // Snippet: SetIamPolicy(string,Policy,CallSettings) // Create client DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); // Initialize request argument(s) string formattedResource = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(); Policy policy = new Policy(); // Make the request Policy response = databaseAdminClient.SetIamPolicy(formattedResource, policy); // End snippet }
public void TestIamPermissions() { // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings) // Create client DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); // Initialize request argument(s) string formattedResource = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(); IEnumerable <string> permissions = new List <string>(); // Make the request TestIamPermissionsResponse response = databaseAdminClient.TestIamPermissions(formattedResource, permissions); // End snippet }
static public DataTable executeQuery(DatabaseName databaseName, String query) { DataTable dataTable = new DataTable(); MySqlConnection mySqlConnection = new MySqlConnection(SQLData.ConnStr(databaseName.ToString())); mySqlConnection.Open(); MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, mySqlConnection); mySqlDataAdapter.Fill(dataTable); mySqlConnection.Close(); return(dataTable); }
private ForeignKeyAssociationMappingConfiguration(ForeignKeyAssociationMappingConfiguration source) { DebugCheck.NotNull(source); _keyColumnNames.AddRange(source._keyColumnNames); _tableName = source._tableName; foreach (var annotation in source._annotations) { _annotations.Add(annotation); } }
/// <summary>Snippet for BatchCreateSessions</summary> public void BatchCreateSessions() { // Snippet: BatchCreateSessions(DatabaseName,int,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); int sessionCount = 0; // Make the request BatchCreateSessionsResponse response = spannerClient.BatchCreateSessions(database, sessionCount); // End snippet }
private static async Task SetupAsync(EmulatorRunner emulatorRunner) { Console.WriteLine(""); Console.WriteLine("Starting emulator..."); emulatorRunner.StartEmulator().WaitWithUnwrappedExceptions(); Console.WriteLine(""); DatabaseName databaseName = DatabaseName.FromProjectInstanceDatabase(s_projectId, s_instanceId, s_databaseId); await MaybeCreateInstanceOnEmulatorAsync(databaseName.ProjectId, databaseName.InstanceId); await MaybeCreateDatabaseOnEmulatorAsync(databaseName); }
private bool HasResourcePrefixHeader(CallSettings callSettings) { var expectedDatabaseName = DatabaseName.FromProjectInstanceDatabase( SpannerClientHelpers.ProjectId, SpannerClientHelpers.Instance, SpannerClientHelpers.Database); var metadata = new Metadata(); callSettings.HeaderMutation?.Invoke(metadata); Metadata.Entry entry = Assert.Single(metadata, e => e.Key == SpannerClientImpl.ResourcePrefixHeader); return(expectedDatabaseName.ToString() == entry.Value); }
public static void RaisePublishing([NotNull] object sender, int mode, [NotNull] DatabaseName databaseName) { Assert.ArgumentNotNull(sender, nameof(sender)); Assert.ArgumentNotNull(databaseName, nameof(databaseName)); var publishing = Publishing; if (publishing != null) { publishing(sender, mode, databaseName); } }
public static DataTable AllView(this DatabaseName databaseName) { string SQL = @" SELECT SCHEMA_NAME(schema_id) AS schema_name ,name AS view_name ,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed ,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable FROM sys.views "; return(Use(databaseName, SQL)); }
public static SqlPreCommand RemoveAllScript(DatabaseName databaseName) { var schemas = SqlBuilder.SystemSchemas.ToString(a => "'" + a + "'", ", "); return(SqlPreCommand.Combine(Spacing.Double, new SqlPreCommandSimple(Use(databaseName, RemoveAllProceduresScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllViewsScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllConstraintsScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllTablesScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllSchemasScript.FormatWith(schemas))) )); }
public void CreateIndex() { // Snippet: CreateIndex(string,Index,CallSettings) // Create client FirestoreAdminClient firestoreAdminClient = FirestoreAdminClient.Create(); // Initialize request argument(s) string formattedParent = new DatabaseName("[PROJECT]", "[DATABASE]").ToString(); Index index = new Index(); // Make the request Operation response = firestoreAdminClient.CreateIndex(formattedParent, index); // End snippet }
public void DropDatabase() { // Snippet: DropDatabase(DatabaseName,CallSettings) // Create client DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); // Initialize request argument(s) DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); // Make the request databaseAdminClient.DropDatabase(database); // End snippet }
protected virtual void Handle([NotNull] NewItemWizardPipeline pipeline, [NotNull] DatabaseName databaseName, [NotNull] ProjectItem projectItem, [NotNull] string itemPath, [NotNull] ProcessedEventHandler callback) { Debug.ArgumentNotNull(pipeline, nameof(pipeline)); Debug.ArgumentNotNull(databaseName, nameof(databaseName)); Debug.ArgumentNotNull(projectItem, nameof(projectItem)); Debug.ArgumentNotNull(itemPath, nameof(itemPath)); Debug.ArgumentNotNull(callback, nameof(callback)); var projectFile = (ProjectFileItem)projectItem; var site = projectItem.Project.Site; if (site == null) { return; } var databaseUri = new DatabaseUri(site, databaseName); var name = Path.GetFileNameWithoutExtension(projectItem.Path); GetItemsCompleted <ItemPath> completed = delegate(IEnumerable <ItemPath> items) { if (!items.Any()) { callback(this, new ProcessedEventArgs(Resources.PathBasedFileItemHandler_Create_failed, Resources.PathBasedFileItemHandler_Create_Path_was_not_created)); return; } // create item var parentUri = items.First().ItemUri; var templateuri = new ItemUri(databaseUri, TemplateId); var itemUri = site.DataService.AddFromTemplate(parentUri, templateuri, name); UpdateFields(pipeline, projectItem, itemUri); // done projectFile.Items.Add(itemUri); callback(this, new ProcessedEventArgs(Resources.PathBasedFileItemHandler_Create_created, Path.GetDirectoryName(itemPath) + @"/" + name)); Notifications.RaiseItemAdded(this, new ItemVersionUri(itemUri, LanguageManager.CurrentLanguage, Version.Latest), parentUri); if (AppHost.CurrentContentTree != null) { AppHost.CurrentContentTree.Locate(itemUri); } }; site.DataService.CreateItemPath(databaseUri, (Path.GetDirectoryName(itemPath) ?? string.Empty).Replace('\\', '/'), completed); }
//Creates a client that will log created sessions in the _createdSession dictionary. private Mock <SpannerClient> CreateMockClient(DatabaseName dbName = null) { var mockClient = new Mock <SpannerClient>(); if (dbName == null) { dbName = s_defaultName; } var sessionList = new List <Session>(); _createdSessions.TryAdd(mockClient, sessionList); mockClient.Setup( x => x.CreateSessionAsync( It.Is <DatabaseName>(y => y.Equals(dbName)), It.IsAny <CancellationToken>())) .ReturnsAsync( () => { var mockSession = new Session { Name = $"{s_defaultName}/sessions/{Guid.NewGuid()}" }; lock (sessionList) { sessionList.Add(mockSession); } return(mockSession); }); mockClient.Setup( x => x.BeginTransactionAsync(It.IsAny <BeginTransactionRequest>(), It.IsAny <CallSettings>())) .ReturnsAsync( () => { var tx = new Transaction { Id = ByteString.CopyFromUtf8(Guid.NewGuid().ToString()) }; _transactions.Push(tx); return(tx); }); mockClient.Setup( x => x.CommitAsync( It.IsAny <SessionName>(), It.IsAny <ByteString>(), It.IsAny <IEnumerable <Mutation> >(), It.IsAny <CallSettings>())) .ReturnsAsync(() => new CommitResponse()); mockClient.Setup(x => x.Settings).Returns(() => SpannerSettings.GetDefault()); return(mockClient); }
public override IDocEntity SaveChanges(bool ignoreCache, DocConstantPermission permission) { DatabaseName = DatabaseName?.TrimAndPruneSpaces(); LibraryPackageName = LibraryPackageName?.TrimAndPruneSpaces(); Number = Number?.TrimAndPruneSpaces(); OperationsDeliverable = OperationsDeliverable?.TrimAndPruneSpaces(); OpportunityId = OpportunityId?.TrimAndPruneSpaces(); OpportunityName = OpportunityName?.TrimAndPruneSpaces(); PICO = PICO?.TrimAndPruneSpaces(); ProjectId = ProjectId?.TrimAndPruneSpaces(); ProjectName = ProjectName?.TrimAndPruneSpaces(); return(base.SaveChanges(ignoreCache, permission)); }
private ManyToManyAssociationMappingConfiguration(ManyToManyAssociationMappingConfiguration source) { DebugCheck.NotNull(source); _leftKeyColumnNames.AddRange(source._leftKeyColumnNames); _rightKeyColumnNames.AddRange(source._rightKeyColumnNames); _tableName = source._tableName; foreach (var annotation in source._annotations) { _annotations.Add(annotation); } }
public override void WriteToStream(IndentStream stream) { stream.Write("ALTER DATABASE "); DatabaseName.WriteToStream(stream); stream.Write(" "); ActionExpr.WriteToStream(stream); if (IsSemicolon) { stream.Write(" ;"); } }
public static EntityType FindTableByName(this EdmModel database, DatabaseName tableName) { DebugCheck.NotNull(tableName); return(database.EntityTypes.SingleOrDefault( t => { var databaseName = t.GetTableName(); return databaseName != null ? databaseName.Equals(tableName) : string.Equals(t.Name, tableName.Name, StringComparison.Ordinal); })); }
public void TestCreateBackup() { var databaseAdminClient = DatabaseAdminClient.Create(); var database = databaseAdminClient.GetDatabase(DatabaseName.FromProjectInstanceDatabase(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.BackupDatabaseId)); var earliestVersionTime = database.EarliestVersionTime.ToDateTime(); CreateBackupSample createBackupSample = new CreateBackupSample(); // Backup already exists since it was created in the test setup so it should throw an exception. var exception = Assert.Throws <RpcException>(() => createBackupSample.CreateBackup(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.BackupDatabaseId, _spannerFixture.BackupId, earliestVersionTime)); Assert.Equal(StatusCode.AlreadyExists, exception.StatusCode); }
public override bool Exists(DatabaseName dname) { try { string SQL = sp_databases(provider); var dnames = DataExtension.FillDataTable(provider, SQL).ToArray<string>("DATABASE_NAME"); return dnames.FirstOrDefault(row => row.ToLower().Equals(dname.Name.ToLower())) != null; } catch (Exception) { } return false; }
/// <summary> /// Configures the table name that this entity type is mapped to. /// </summary> /// <param name="tableName"> The name of the table. </param> /// <remarks> /// Calling this will have no effect once it has been configured. /// </remarks> public LightweightEntityConfiguration ToTable(string tableName) { Check.NotEmpty(tableName, "tableName"); if (!_configuration().IsTableNameConfigured) { var databaseName = DatabaseName.Parse(tableName); _configuration().ToTable(databaseName.Name, databaseName.Schema); } return(this); }
protected virtual string CreateDatabase(DisconnectedMachineEntity machine) { DatabaseName databaseName = DatabaseName(machine); DisconnectedTools.DropIfExists(databaseName); string fileName = DatabaseFileName(machine); string logFileName = DatabaseLogFileName(machine); DisconnectedTools.CreateDatabase(databaseName, fileName, logFileName); return(((SqlServerConnector)Connector.Current).ConnectionString.Replace(Connector.Current.DatabaseName(), databaseName.Name)); }
public override void CleanDatabase(DatabaseName database) { string fileName = new SqlCeConnection(connectionString).DataSource; if (File.Exists(fileName)) { File.Delete(fileName); } SqlCeEngine en = new SqlCeEngine(connectionString); en.CreateDatabase(); }
public static SqlPreCommand RemoveAllScript(DatabaseName databaseName) { var schemas = SqlBuilder.SystemSchemas.ToString(a => "'" + a + "'", ", "); return(SqlPreCommand.Combine(Spacing.Double, new SqlPreCommandSimple(Use(databaseName, RemoveAllProceduresScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllViewsScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllConstraintsScript)), Connector.Current.SupportsTemporalTables ? new SqlPreCommandSimple(Use(databaseName, StopSystemVersioning)) : null, new SqlPreCommandSimple(Use(databaseName, RemoveAllTablesScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllSchemasScript.FormatWith(schemas))) )); }
private static string GetDatabaseFilePath(WarcraftVersion version, DatabaseName databaseName) { var path = Path.Combine ( TestContext.CurrentContext.WorkDirectory, "Content", version.ToString(), "DBFilesClient", $"{databaseName}.dbc" ); return(path); }
private Session CreateSession(DatabaseName database) { var id = Interlocked.Increment(ref _sessionCounter); Session session = new Session { SessionName = new SessionName(database.ProjectId, database.InstanceId, database.DatabaseId, $"session-{id}") }; if (!_sessions.TryAdd(session.SessionName, session)) { throw new RpcException(new Grpc.Core.Status(StatusCode.AlreadyExists, $"Session with id session-{id} already exists")); } return(session); }
private static bool IsTableNameEqual(EntityType table, DatabaseName otherTableName) { var tableName = table.GetTableName(); if (tableName != null) { return(otherTableName.Equals(tableName)); } else { return(otherTableName.Name.Equals(table.Name, StringComparison.Ordinal) && otherTableName.Schema == null); } }
/// <inheritdoc /> public override int GetHashCode() { unchecked { var hashCode = DatabaseName != null?DatabaseName.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (TableName != null ? TableName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Code != null ? Code.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (FileName != null ? FileName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ClassName != null ? ClassName.GetHashCode() : 0); return(hashCode); } }
/// <summary> /// Formats a database table name to a <code>Schema.TableName</code> pattern. /// Schema name is optional; if no schema is specified then the /// default schema from the <see cref="System.Data.SqlClient.SqlConnection"/> is assumed. /// </summary> /// <param name="tableName">The name of the table, standardized or not.</param> /// <returns>A standardized database table name.</returns> private string GetStandardizedTableName(string tableName) { DebugCheck.NotNullOrWhiteSpace(tableName); var databaseName = DatabaseName.Parse(tableName); if (!string.IsNullOrWhiteSpace(databaseName.Schema)) { return(tableName); } return(new DatabaseName(tableName, DefaultSchema).ToString()); }
public bool Execute(string SelectStatement = "*") { string Provider = ""; bool Success = false; using (OleDbConnection cn = new OleDbConnection { ConnectionString = DatabaseName.BuildConnectionString() }) { using (OleDbCommand cmd = new OleDbCommand { Connection = cn }) { // // Determine the proper provider for Excel // if (Path.GetExtension(DatabaseName).ToLower() == ".mdb" && Path.GetExtension(ExcelFileName).ToLower() == ".xls") { Provider = "Excel 8.0;"; } else if (Path.GetExtension(DatabaseName).ToLower() == ".accdb" && Path.GetExtension(ExcelFileName).ToLower() == ".xlsx") { Provider = "Excel 12.0 xml;"; } cmd.CommandText = $"SELECT {SelectStatement} INTO [{Provider}DATABASE={ExcelFileName};HDR=No].[{WorkSheetName}] FROM [{TableName}]"; cn.Open(); try { // if you need, affected is the row count placed into the destination worksheet RecordsInserted = cmd.ExecuteNonQuery(); Success = RecordsInserted > 0; } catch (Exception ex) { // // If we get here and the exception is -> Data type mismatch in criteria expression // the data type is not valid e.g. you attempted to place a binary field such as an image into the worksheet. // We could query each field's data type and make a decision to abort and if so that needs to happen before // cmd.ExecuteNonQuery() as after the fact the WorkSheet has already been created, the exception is raised // after the Worksheet has been created so now you need to clean up and remove the WorkSheet which is beyond // the scope of this code sample. // ' ExceptionMessage = ex.Message; } } } return(Success); }
public override bool Validate(out Dictionary <string, string> errors) { errors = new Dictionary <string, string>(); if (string.IsNullOrEmpty(Name)) { errors.Add(nameof(Name), "Criterio name is mandatory."); } if (criterioType == QCriterioType.Unspecified) { errors.Add(nameof(CriterioType), "Criterio type is mandatory."); } if (string.IsNullOrEmpty(categoryDesc)) { errors.Add(nameof(CategoryDesc), "Category is mandatory."); } if (DatabaseName.IsInvalid()) { errors.Add(nameof(DatabaseName), "Check DatabaseName."); } if (string.IsNullOrEmpty(whereTable)) { errors.Add(nameof(WhereTable), "TableName is mandatory."); } if (string.IsNullOrEmpty(whereField)) { errors.Add(nameof(WhereField), "FieldName is mandatory."); } if (Name.HasTrailingSpaces()) { errors.Add(nameof(Name), "Trailing spaces are not allowed."); } if (WhereField.HasTrailingSpaces()) { errors.Add(nameof(WhereField), "Trailing spaces are not allowed."); } if (WhereTable.HasTrailingSpaces()) { errors.Add(nameof(WhereTable), "Trailing spaces are not allowed."); } if (string.IsNullOrEmpty(crjCode)) { errors.Add(nameof(CrjCode), "CrjCode is mandatory."); } return(errors.Count == 0); }
private EntityMappingConfiguration(EntityMappingConfiguration source) { DebugCheck.NotNull(source); _tableName = source._tableName; MapInheritedProperties = source.MapInheritedProperties; if (source._properties != null) { _properties = new List<PropertyPath>(source._properties); } _valueConditions.AddRange(source._valueConditions.Select(c => c.Clone(this))); _notNullConditions.AddRange(source._notNullConditions.Select(c => c.Clone(this))); }
public virtual void RestoreLocalDatabase(string connectionString, string backupFile, string databaseFile, string databaseLogFile) { FileTools.CreateParentDirectory(databaseFile); var csb = new SqlConnectionStringBuilder(connectionString); DatabaseName databaseName = new DatabaseName(null, csb.InitialCatalog); csb.InitialCatalog = ""; using (SqlConnector.Override(new SqlConnector(csb.ToString(), null, null, SqlServerVersion.SqlServer2012))) { DropIfExists(databaseName); RestoreDatabase(databaseName, backupFile, databaseFile, databaseLogFile); } }
public static void RestoreDatabase(DatabaseName databaseName, string backupFile, string databaseFile, string databaseLogFile, bool replace = false) { DataTable dataTable = Executor.ExecuteDataTable("RESTORE FILELISTONLY FROM DISK ='{0}'".FormatWith(backupFile)); string logicalDatabaseFile = dataTable.AsEnumerable().Single(a => a.Field<string>("Type") == "D").Field<string>("LogicalName"); string logicalDatabaseLogFile = dataTable.AsEnumerable().Single(a => a.Field<string>("Type") == "L").Field<string>("LogicalName"); new SqlPreCommandSimple( @"RESTORE DATABASE {0} from DISK = '{1}' WITH MOVE '{2}' TO '{3}', MOVE '{4}' TO '{5}'{6}".FormatWith(databaseName, backupFile, logicalDatabaseFile, databaseFile, logicalDatabaseLogFile, databaseLogFile, replace ? ",\r\nREPLACE" : "")).ExecuteNonQuery(); }
public Dependency(DatabaseName dname) { var dt = dname .Provider .Schema .GetDependencySchema(dname) .AsEnumerable(); rows = dt.Select( row => new RowDef { fkTable = new TableName(dname, (string)row["FK_SCHEMA"], (string)row["FK_Table"]), pkTable = new TableName(dname, (string)row["PK_SCHEMA"], (string)row["PK_Table"]), pkColumn = (string)row["PK_Column"], fkColumn = (string)row["FK_Column"] }) .ToArray(); }
public static string DatabaseDifference(CompareSideType sideType, DatabaseName dname1, DatabaseName dname2, string[] excludedTables) { TableName[] names = dname1.GetDependencyTableNames(); excludedTables = excludedTables.Select(row => row.ToUpper()).ToArray(); StringBuilder builder = new StringBuilder(); foreach (TableName tableName in names) { TableName tname1 = tableName; TableName tname2 = new TableName(dname2, tableName.SchemaName, tableName.Name); TableSchema schema1 = new TableSchema(tname1); TableSchema schema2 = new TableSchema(tname2); Console.WriteLine(tname1.ShortName); if (excludedTables.Contains(tableName.ShortName.ToUpper())) { Console.WriteLine("skip to compare data on excluded table {0}", tableName.ShortName); continue; } if (schema1.PrimaryKeys.Length == 0) { Console.WriteLine("undefined primary key"); continue; } if (tname2.Exists()) { builder.Append(TableDifference(sideType, schema1, schema2, schema1.PrimaryKeys.Keys, new string[] { })); } else { builder.Append(Compare.GenerateRows(schema1, new TableReader(tname1))); } builder.AppendLine(); } return builder.ToString(); }
public DataTableDpoClass(DataTable table) { DatabaseName dname = new DatabaseName(ConnectionProviderManager.DefaultProvider, "MEM"); this.table = table; this.tableName = new ClassTableName(new TableName(dname, TableName.dbo, table.TableName)); this._columns = new ColumnCollection(this); foreach (DataColumn c in table.Columns) { this._columns.Add(new DtColumn(c)); } this._identity = new IdentityKeys(this._columns); this._computedColumns = new ComputedColumns(this._columns); this._columns.UpdatePrimary(this.PrimaryKeys); this._columns.UpdateForeign(this.ForeignKeys); }
public static void ClassInitialize(TestContext testContext) { IDatabaseService provider = UserDatabaseTests.CreateProvider(); using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(600)))) { ReadOnlyCollection<DatabaseFlavor> flavors = provider.ListFlavorsAsync(cancellationTokenSource.Token).Result; if (flavors.Count == 0) Assert.Inconclusive("The service did not report any flavors."); DatabaseFlavor smallestFlavor = flavors.Where(i => i.Memory.HasValue).OrderBy(i => i.Memory).First(); string instanceName = UserDatabaseTests.CreateRandomDatabaseInstanceName(); DatabaseInstanceConfiguration configuration = new DatabaseInstanceConfiguration(smallestFlavor.Href, new DatabaseVolumeConfiguration(1), instanceName); _instance = provider.CreateDatabaseInstanceAsync(configuration, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null).Result; _databaseName = UserDatabaseTests.CreateRandomDatabaseName(); DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration(_databaseName, null, null); provider.CreateDatabaseAsync(_instance.Id, databaseConfiguration, cancellationTokenSource.Token).Wait(); _databaseName2 = UserDatabaseTests.CreateRandomDatabaseName(); DatabaseConfiguration databaseConfiguration2 = new DatabaseConfiguration(_databaseName2, null, null); provider.CreateDatabaseAsync(_instance.Id, databaseConfiguration2, cancellationTokenSource.Token).Wait(); } }
public TableName[] GetDependencyTableNames(DatabaseName databaseName) { var dict = rows.GroupBy( row => row.fkTable, (Key, rows) => new { FkTable = Key, PkTables = rows.Select(row => row.pkTable).ToArray() }) .ToDictionary(row => row.FkTable, row => row.PkTables); TableName[] names = databaseName.GetTableNames(); List<TableName> history = new List<TableName>(); foreach (var tname in names) { if (history.IndexOf(tname) < 0) Iterate(tname, dict, history); } return history.ToArray(); }
private static string Replace(string connectionString, DatabaseName item) { var csb = new SqlConnectionStringBuilder(connectionString); csb.InitialCatalog = item.ToString(); return csb.ToString(); }
public void ToDatabase(DatabaseName databaseName) { this.Name = this.Name.OnDatabase(databaseName); }
public void ToDatabase(DatabaseName databaseName) { this.Name = this.Name.OnDatabase(databaseName); foreach (var item in TablesMList()) item.ToDatabase(databaseName); }
public ClassTableName(DatabaseName databaseName, string tableName) : this(new TableName(databaseName, TableName.dbo, tableName)) { }
public static SqlPreCommand RemoveAllScript(DatabaseName databaseName) { var schemas = SqlBuilder.SystemSchemas.ToString(a => "'" + a + "'", ", "); return SqlPreCommand.Combine(Spacing.Double, new SqlPreCommandSimple(Use(databaseName, RemoveAllProceduresScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllViewsScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllConstraintsScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllTablesScript)), new SqlPreCommandSimple(Use(databaseName, RemoveAllSchemasScript.FormatWith(schemas))) ); }
static string Use(DatabaseName databaseName, string script) { if (databaseName == null) return script; return "use " + databaseName + "\r\n" + script; }