protected override void ModifyRequest(TransactionalRequestJob requestJob) { base.ModifyRequest(requestJob); if (base.IsFieldSet("SourceDatabase")) { PublicFolderDatabase publicFolderDatabase = (PublicFolderDatabase)base.GetDataObject <PublicFolderDatabase>(this.SourceDatabase, base.ConfigSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(this.SourceDatabase.ToString())), new LocalizedString?(Strings.ErrorDatabaseNotUnique(this.SourceDatabase.ToString()))); DatabaseInformation databaseInformation = MapiUtils.FindServerForMdb(publicFolderDatabase.Id.ObjectGuid, null, null, FindServerFlags.None); if (!this.IsSupportedDatabaseVersion(databaseInformation.ServerVersion)) { base.WriteError(new DatabaseVersionUnsupportedPermanentException(publicFolderDatabase.Identity.ToString(), databaseInformation.ServerFqdn, new ServerVersion(databaseInformation.ServerVersion).ToString()), ErrorCategory.InvalidArgument, null); } requestJob.SourceDatabase = publicFolderDatabase.Id; } if (base.IsFieldSet("RemoteMailboxLegacyDN")) { requestJob.RemoteMailboxLegacyDN = this.RemoteMailboxLegacyDN; } if (base.IsFieldSet("RemoteMailboxServerLegacyDN")) { requestJob.RemoteMailboxServerLegacyDN = this.RemoteMailboxServerLegacyDN; } if (base.IsFieldSet("OutlookAnywhereHostName")) { requestJob.OutlookAnywhereHostName = this.OutlookAnywhereHostName; } if (base.IsFieldSet("AuthenticationMethod")) { requestJob.AuthenticationMethod = new AuthenticationMethod?(this.AuthenticationMethod); } if (base.IsFieldSet("RemoteCredential")) { requestJob.RemoteCredential = RequestTaskHelper.GetNetworkCredential(this.RemoteCredential, requestJob.AuthenticationMethod); } }
/// <summary> /// CreateCoreDatabase() creates the database if it doesn't exist. /// </summary> private void CreateCoreDatabase() { MySqlConnection connection = null; try { DatabaseInformation databaseInformation = new DatabaseInformation(); // Because the parameter in ConnectionString is false, the connection string // doesn't contain a database parameter. connection = new MySqlConnection(databaseInformation.ConnectionString(false)); connection.Open(); string databaseExist = "CREATE DATABASE IF NOT EXISTS `" + connectionSettings._DatabaseName + "`;"; MySqlCommand msc = new MySqlCommand(databaseExist, connection); msc.ExecuteNonQuery(); } catch (MySqlException e) { Console.WriteLine(e); } finally { if (connection != null) { connection.Close(); } } }
private void RetrieveTargetMailboxInformation() { if (base.IsFieldSet("TargetDatabase")) { this.targetMailboxDatabase = (MailboxDatabase)base.GetDataObject <MailboxDatabase>(this.TargetDatabase, base.ConfigSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(this.TargetDatabase.ToString())), new LocalizedString?(Strings.ErrorDatabaseNotUnique(this.TargetDatabase.ToString()))); MailboxTaskHelper.VerifyDatabaseIsWithinScopeForRecipientCmdlets(base.ConfigSession.SessionSettings, this.targetMailboxDatabase, new Task.ErrorLoggerDelegate(base.WriteError)); } else { this.targetMailboxDatabase = this.ChooseTargetMailboxDatabase(this.mailbox.Database); } DatabaseInformation value = MapiUtils.FindServerForMdb(this.targetMailboxDatabase.Id.ObjectGuid, null, null, FindServerFlags.None); this.targetDatabaseInformation = new DatabaseInformation?(value); if (!this.IsSupportedDatabaseVersion(value.ServerVersion, NewRequest <MailboxRelocationRequest> .DatabaseSide.Target)) { base.WriteError(new DatabaseVersionUnsupportedPermanentException(this.targetMailboxDatabase.Identity.ToString(), value.ServerFqdn, new ServerVersion(value.ServerVersion).ToString()), ErrorCategory.InvalidArgument, this.Mailbox); } if (this.targetMailboxDatabase.Recovery) { base.WriteError(new RecipientTaskException(Strings.ErrorTargetDatabaseIsRecovery(this.targetMailboxDatabase.ToString())), ErrorCategory.InvalidArgument, this.Mailbox); } if (this.mailbox.MailboxProvisioningConstraint != null && this.targetMailboxDatabase.MailboxProvisioningAttributes != null && !this.mailbox.MailboxProvisioningConstraint.IsMatch(this.targetMailboxDatabase.MailboxProvisioningAttributes)) { base.WriteError(new MailboxConstraintsMismatchException(this.mailbox.ToString(), this.targetMailboxDatabase.Name, this.mailbox.MailboxProvisioningConstraint.Value), ErrorCategory.InvalidData, this.Mailbox); } }
public int SaveDatabase(DatabaseDTO message) { using (var projectContext = new DataAccess.MyProjectEntities()) { var dbDatabase = projectContext.DatabaseInformation.FirstOrDefault(x => x.ID == message.ID); if (dbDatabase == null) { dbDatabase = new DatabaseInformation(); dbDatabase.SecurityObject = new SecurityObject(); dbDatabase.SecurityObject.Type = (int)DatabaseObjectCategory.Database; } dbDatabase.DBServerID = message.DBServerID; dbDatabase.Name = message.Name; dbDatabase.Title = message.Title; dbDatabase.DBHasDate = message.DBHasData; dbDatabase.ConnectionString = message.ConnectionString; dbDatabase.DBType = message.DBType.ToString(); if (dbDatabase.ID == 0) { projectContext.DatabaseInformation.Add(dbDatabase); } projectContext.SaveChanges(); return(dbDatabase.ID); } }
/// <summary> /// Wrapper for multiple Sql calls across multiple databases within a transaction /// </summary> /// <remarks>This will use individual connections using a distributed transactions (performance hit)</remarks> /// <param name="logger">The logger for the transaction sequence</param> /// <param name="method">The actual SQL calls</param> /// <param name="exceptionMethod">Default = ExceptionRethrow. If an exception is thrown during "method", how will it be handled (besides being rolled back)</param> /// <returns>True if the transaction was committed, false if rolled back</returns> public static async Task <bool> Distributed(ILogger logger, Func <Task <TransactionResponse> > method, Func <Exception, bool> exceptionMethod = null) { DatabaseInformation info = null; if (logger != null) { info = logger.DatabaseEntry("Database Transaction", "Action Distributed Transaction"); } using var scope = new TransactionScope(); var success = await SafeTry.OnException( async() => { var response = await method(); if (response.Success) { scope.Complete(); } return(response.Success); }, exceptionMethod); if (logger != null) { logger.DatabaseExit(info); } return(success); }
/// <summary> /// Wrapper for multiple Sql calls across multiple databases within a transaction /// </summary> /// <remarks>This will use individual connections using a distributed transactions (performance hit)</remarks> /// <typeparam name="T">Return type of the complete transaction</typeparam> /// <param name="logger">The logger for the transaction sequence</param> /// <param name="method">The actual SQL calls</param> /// <param name="exceptionMethod">Default = ExceptionRethrow. If an exception is thrown during "method", how will it be handled (besides being rolled back)</param> /// <param name="defaultValue">Default = Default(T). If an exception is thrown during "method", and it is not rethrowing the exception, this will instead be returned</param> /// <returns>The result from the SQL calls (method) - or possibly default(T) if there was an exception</returns> public static async Task <T> Distributed <T>(ILogger logger, Func <Task <TransactionResponse <T> > > method, Func <Exception, T, T> exceptionMethod, T defaultValue = default) { DatabaseInformation info = null; if (logger != null) { info = logger.DatabaseEntry("Database Transaction", "Func Distributed Transaction"); } using var scope = new TransactionScope(); var result = await SafeTry.OnException( async() => { var response = await method(); if (response.Success) { scope.Complete(); } return(response.Response); }, ex => exceptionMethod(ex, defaultValue)); if (logger != null) { logger.DatabaseExit(info); } return(result); }
private void ConnectToDb() { string filePath = Directory.GetCurrentDirectory() + @"\system.ini"; dbInfo = FstDatabaseInformationReader.GetFromIni(filePath, "STDB"); dbAgent = DbAgentFactory.CreateDbAgent(dbInfo); }
private MailboxDatabase LocateAndVerifyMdb(DatabaseIdParameter databaseId, out ServerVersion targetServerVersion) { MailboxDatabase mailboxDatabase = (MailboxDatabase)base.GetDataObject <MailboxDatabase>(databaseId, base.ConfigSession, null, new LocalizedString?(Strings.ErrorMailboxDatabaseNotFound(databaseId.ToString())), new LocalizedString?(Strings.ErrorMailboxDatabaseNotUnique(databaseId.ToString()))); DatabaseInformation databaseInformation = MapiUtils.FindServerForMdb(mailboxDatabase.Id.ObjectGuid, null, null, FindServerFlags.None); targetServerVersion = new ServerVersion(databaseInformation.ServerVersion); this.EnsureSupportedServerVersion(databaseInformation.ServerVersion); return(mailboxDatabase); }
public virtual IConnectionProvider Create(DatabaseInformation databaseInformation) { switch (databaseInformation.DatabaseType.ToLower()) { case "sqlserver": return(new SqlConnectionProvider(databaseInformation)); default: return(null); } }
private void BindDatabaseDetails(Database selectedDatabase) { if (selectedDatabase == null) { detailsPropertyGrid.SelectedObject = null; } else { DatabaseInformation databaseInformation = new DatabaseInformation(selectedDatabase); detailsPropertyGrid.SelectedObject = databaseInformation; } }
private void ClearStructures() { if (this.schemaManager != null) { this.schemaManager.ClearStructures(); } this.granteeManager = null; this.userManager = null; this.NameManager = null; this.schemaManager = null; this.DbInfo = null; }
protected string BuildConnectionString(DatabaseInformation databaseInformation) { var connectionStringBuilder = new SqlConnectionStringBuilder { DataSource = this.GlobalConfigurationService.ConfigurationManager.Database.Connection.Host, InitialCatalog = databaseInformation.DatabaseName, UserID = databaseInformation.Username, Password = databaseInformation.Password }; return(connectionStringBuilder.ToString()); }
public virtual DatabaseInformation Create(DatabasePropertyReaderBase propertyReader) { DatabaseInformation dbInformation = null; switch (propertyReader.DatabaseType?.ToLower()) { case "sqlserver": dbInformation = new SqlDatabaseInformation(propertyReader); break; } return(dbInformation); }
private IDataAccessService GetDataAccessService(DatabaseInformation dbInfo) { if (DataAccessServices.TryGetValue(dbInfo, out var dataService)) { return(dataService); } dataService = ServiceProvider.GetService <IDataAccessService>(); dataService.DatabaseInformation = dbInfo; DataAccessServices.Add(dbInfo, dataService); return(dataService); }
internal void SetInformations(DatabaseInformation dbInformation, IDbConnection connection = null, IDbTransaction transaction = null, object parameters = null, object replacement = null, CommandType?commandType = null, int?commandTimeout = null) { DatabaseName = dbInformation.Name; DatabaseType = dbInformation.DatabaseType; ConnectionString = dbInformation.ConnectionString; Connection = connection; Transaction = transaction; Parameters = parameters; Replacements = replacement; CommandType = commandType; CommandTimeout = commandTimeout ?? dbInformation.CommandTimeout; }
public void Initialize() { dbInfo = Utility.CreateSeededTestDatabase(); using (var context = new EntitiesContext(dbInfo.ConnectionString)) using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context)) { IChoreService service = new ChoreService(unitOfWork.RepositoryAsync<Chore>()); ChoresController controller = new ChoresController(unitOfWork, service, new FakeTimeService(new DateTime(2015, 11, 1))) .SetControllerContext(HttpMethod.Post, "http://localhost/RowanAdams/api/chores"); var result = controller.Post(new Chore { Name = "Test Chore 1", Value = 10 }); result.Wait(); } }
private DatabaseSettingDTO GetDatabaseSetting(DatabaseInformation item) { if (item.DatabaseUISetting != null) { DatabaseSettingDTO result = new DatabaseSettingDTO(); result.FlowDirectionLTR = item.DatabaseUISetting.FlowDirectionLTR; result.ShowMiladiDateInUI = item.DatabaseUISetting.ShowMiladiDateInUI; result.StringDateColumnIsMiladi = item.DatabaseUISetting.StringDateColumnIsMiladi; return(result); } else { return(null); } }
protected T CheckDatabase <T>(DatabaseIdParameter databaseIdParameter, NewRequest <TRequest> .DatabaseSide databaseSide, object errorObject, out string serverName, out string serverDN, out ADObjectId serverSite, out int serverVersion) where T : Database, new() { T result = (T)((object)base.GetDataObject <T>(databaseIdParameter, this.ConfigSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(databaseIdParameter.ToString())), new LocalizedString?(Strings.ErrorDatabaseNotUnique(databaseIdParameter.ToString())))); DatabaseInformation databaseInformation = MapiUtils.FindServerForMdb(result.Id.ObjectGuid, null, null, FindServerFlags.None); serverName = databaseInformation.ServerFqdn; serverDN = databaseInformation.ServerDN; serverSite = databaseInformation.ServerSite; serverVersion = databaseInformation.ServerVersion; if (!this.IsSupportedDatabaseVersion(serverVersion, databaseSide)) { base.WriteError(new DatabaseVersionUnsupportedPermanentException(result.Identity.ToString(), serverName, new ServerVersion(serverVersion).ToString()), ErrorCategory.InvalidArgument, errorObject); } return(result); }
protected virtual async Task <DatabaseInformation> CreateDatabaseAsync(Guid moduleId, string password, ModuleInformation moduleInformation) { var databaseInformation = new DatabaseInformation() { Module = moduleInformation, Username = $"ModuleUser_{moduleId:N}", Password = password, DatabaseName = $"ModuleDb_{moduleId:N}", }; await this.Context.Databases.AddAsync(databaseInformation); await this.Context.SaveChangesAsync(); return(databaseInformation); }
private void Reopen() { this.SetState(4); try { this.NameManager = new QNameManager(this); this.granteeManager = new GranteeManager(this); this.userManager = new UserManager(this); this.schemaManager = new SchemaManager(this); this.persistentStoreCollection = new PersistentStoreCollectionDatabase(); this._isReferentialIntegrity = true; this.sessionManager = new SessionManager(this); this.collation = Collation.GetDefaultInstance(); this.DbInfo = DatabaseInformation.NewDatabaseInformation(this); this.TxManager = new TransactionManagerMvcc(this); this.lobManager.CreateSchema(); this.sessionManager.GetSysLobSession().SetSchema("SYSTEM_LOBS"); this.schemaManager.SetSchemaChangeTimestamp(); this.logger.OpenPersistence(); if (this.logger.IsNewDatabase) { string property = this.UrlProperties.GetProperty("user", "SA"); string password = this.UrlProperties.GetProperty("password", ""); this.userManager.CreateFirstUser(property, password); this.schemaManager.CreatePublicSchema(); this.lobManager.InitialiseLobSpace(); this.logger.Checkpoint(false); } this.lobManager.Open(); this.DbInfo.SetWithContent(true); } catch (Exception error) { this.logger.ClosePersistence(-1); this.logger.ReleaseLock(); this.SetState(0x10); this.ClearStructures(); DatabaseManager.RemoveDatabase(this); if (!(error is CoreException)) { error = Error.GetError(0x1ca, error); } this.logger.LogSevereEvent(FwNs.Core.LC.cResources.SR.Database_Reopen_could_not_reopen_database, error); throw; } this.SetState(1); }
public void Initialize() { dbInfo = Utility.CreateSeededTestDatabase(); using (var context = new EntitiesContext(dbInfo.ConnectionString)) using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context)) { IChoreService service = new ChoreService(unitOfWork.RepositoryAsync <Chore>()); ChoresController controller = new ChoresController(unitOfWork, service, new FakeTimeService(new DateTime(2015, 11, 1))) .SetControllerContext(HttpMethod.Post, "http://localhost/RowanAdams/api/chores"); var result = controller.Post(new Chore { Name = "Test Chore 1", Value = 10 }); result.Wait(); } }
protected void Button1_Click(object sender, EventArgs e) { if (Page.IsValid) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MicrosoftSQL"].ConnectionString); try { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO csharp(input1, input2, input3, input4, input5) VALUES('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + DropDownList1.Text + "', '" + RadioButtonList1.Text + "', '" + CheckBoxList1.Text + "')"; try { cmd.ExecuteNonQuery(); Label4.Text = "Insert Success"; DatabaseInformation.DataBind(); } catch (Exception ex2) { Label4.Text = "Failed insert:" + ex2.Message; } conn.Close(); conn.Dispose(); } catch (Exception ex) { Label4.Text = "Failed to connect:" + ex.Message; } } }
/// <summary> /// Wrapper for multiple Sql calls (Single database) within a transaction /// </summary> /// <param name="logger">The logger for the transaction sequence</param> /// <param name="cnnStr">The connection string to use for all calls within the transaction</param> /// <param name="method">The actual SQL calls</param> /// <param name="isolation">Default = ReadCommitted. Isolation level for the transaction.</param> /// <param name="exceptionMethod">Default = ExceptionRethrow. If an exception is thrown during "method", how will it be handled (besides being rolled back)</param> /// <returns>True if the transaction was committed, false if rolled back</returns> public static async Task <bool> Run(ILogger logger, string cnnStr, Func <IDbTransaction, Task <TransactionResponse> > method, IsolationLevel isolation, Func <Exception, bool> exceptionMethod) { DatabaseInformation info = null; if (logger != null) { info = logger.DatabaseEntry(cnnStr, "Action Transaction"); } await using var cnn = new TC { ConnectionString = $"{cnnStr};MultipleActiveResultSets=True" }; if (cnn.State != ConnectionState.Open) { await cnn.OpenAsync(); } await using var transaction = await cnn.BeginTransactionAsync(isolation); var success = await SafeTry.OnException( async() => { var response = await method(transaction); if (response.Success) { await transaction.CommitAsync(); } else { await transaction.RollbackAsync(); } return(response.Success); }, async ex => { await transaction.RollbackAsync(); return(exceptionMethod(ex)); }); if (logger != null) { logger.DatabaseExit(info); } return(success); }
private static I_DBHelper GetDBHelper(DatabaseInformation database, bool withTransaction) { I_DBHelper dbHelper = null;//= System.Runtime.Remoting.Messaging.CallContext.GetData(database.Name) as I_DBHelper; if (dbHelper == null) { var dbProvider = GetDatabaseProvider(database); if (dbProvider == DatabaseProvider.SQLServer) { var connection = new SqlConnection(database.ConnectionString); dbHelper = new SQLHelper(connection, withTransaction); //System.Runtime.Remoting.Messaging.CallContext.SetData(database.Name, dbHelper); } else if (dbProvider == DatabaseProvider.Oracle) { } } return(dbHelper); }
public bool CheckDatabase(Config config) { using (var db = GetDatabase(config)) { try { DatabaseInformation info = db.CurrentDatabaseInformation(); Console.WriteLine("=================================="); Console.WriteLine($"Database id : {info.Id}"); Console.WriteLine($"Database Name : {info.Name}"); Console.WriteLine($"Database is system : {info.IsSystem}"); Console.WriteLine($"Database path : {info.Path}"); Console.WriteLine("=================================="); return(true); } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}"); } return(false); } }
public void CheckDatabaseInfoExists() { var context = new MyProjectEntities(); DBServer dbserver = context.DBServer.FirstOrDefault(x => x.Name == "LOCALHOST"); if (dbserver == null) { dbserver = new DBServer(); dbserver.Name = "LOCALHOST"; dbserver.Title = "LOCALHOST"; context.DBServer.Add(dbserver); } if (!context.DatabaseInformation.Any(x => x.Name == "DBProductService")) { DatabaseInformation db = new DatabaseInformation(); db.ConnectionString = "Data Source=LOCALHOST;Initial Catalog=DBProductService;User ID=sa;Password=123;MultipleActiveResultSets=True;";// "Data Source=Localhost;Initial Catalog=DBProductService;Integrated Security=True;MultipleActiveResultSets=True;"; db.Name = "DBProductService"; db.Title = "خدمات و سرويس"; db.DBType = "SQLServer"; db.DBServer = dbserver; db.DBHasDate = false; db.SecurityObject = new SecurityObject(); db.SecurityObject.Type = (int)DatabaseObjectCategory.Database; context.DatabaseInformation.Add(db); } DBServer dbserver2 = context.DBServer.FirstOrDefault(x => x.Name == "LOCALHOST\\SQL_EXP_SALARY"); if (dbserver2 == null) { dbserver2 = new DBServer(); dbserver2.Name = "LOCALHOST\\SQL_EXP_SALARY"; dbserver2.Title = "LOCALHOST\\SQL_EXP_SALARY"; context.DBServer.Add(dbserver2); } if (!context.DatabaseInformation.Any(x => x.Name == "DBProducts")) { DatabaseInformation db = new DatabaseInformation(); db.ConnectionString = "Data Source=LOCALHOST\\SQL_EXP_SALARY;Initial Catalog=DBProducts;Integrated Security=True;MultipleActiveResultSets=True;"; //"Data Source=.\\SQL_EXP_SALARY;Initial Catalog=DBProducts;User ID=sa;Password=123;MultipleActiveResultSets=True;"; db.Name = "DBProducts"; db.Title = "محصولات"; db.DBType = "SQLServer"; db.DBServer = dbserver2; db.DBHasDate = false; db.SecurityObject = new SecurityObject(); db.SecurityObject.Type = (int)DatabaseObjectCategory.Database; context.DatabaseInformation.Add(db); } try { context.SaveChanges(); } catch (DbUpdateException e) { //Add your code to inspect the inner exception and/or //e.Entries here. //Or just use the debugger. //Added this catch (after the comments below) to make it more obvious //how this code might help this specific problem } }
//private DbConnection GetConnection(DatabaseProvider dbProvider, DatabaseDTO databaseDTO) //{ // DbConnection connection = System.Runtime.Remoting.Messaging.CallContext.GetData(databaseDTO.Name) as DbConnection; // if (connection == null) // { // if (dbProvider == DatabaseProvider.SQLServer) // { // connection = new SqlConnection(databaseDTO.ConnectionString); // } // else if (dbProvider == DatabaseProvider.Oracle) // { // } // System.Runtime.Remoting.Messaging.CallContext.SetData(key, connection); // } // return connection; //} //public void SaveChanges() //{ // //if (this.isContextOwner) // //this.GetCurrentDataContext().SaveChanges(); //} //public void Rollback() //{ // //this.GetCurrentDataContext().Rollback(); //} //public void Dispose() //{ // //throw new NotImplementedException(); //} private static DatabaseProvider GetDatabaseProvider(DatabaseInformation databaseDTO) { return(DatabaseProvider.SQLServer); }
public void DatabaseExit(DatabaseInformation info) { }
public SqlPackBuilder DatabaseInformation(DatabaseInformation database) { _dbInformation = database ?? throw new ArgumentNullException(nameof(database)); return(this); }
public virtual void DatabaseExit(DatabaseInformation info) => DoUpdate(info);
public SqlConnectionProvider(DatabaseInformation databaseInformation) { DatabaseInformation = databaseInformation; }