private void metroButton1_Click(object sender, EventArgs e) { IngresConnection con = new IngresConnection(Login.myConnectionString); con.Open(); IngresCommand cmd = new IngresCommand(); cmd.Connection = con; cmd.CommandText = "rol_create"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new IngresParameter("t_id_rol", IngresType.Decimal)); cmd.Parameters.Add(new IngresParameter("t_nombre", IngresType.VarChar)); cmd.Parameters["t_id_rol"].Value = 0; cmd.Parameters["t_nombre"].Value = this.nombre.Text; try { cmd.ExecuteNonQuery(); MetroMessageBox.Show(this, "Elemento creado correctamente.", "Nota", MessageBoxButtons.OK, MessageBoxIcon.Question); } catch (IngresException c) { MetroMessageBox.Show(this, c.ErrorCode + c.Message, "Error"); } con.Close(); this.read(); }
private void Delete_Click(object sender, EventArgs e) { IngresConnection con = new IngresConnection(Login.myConnectionString); con.Open(); IngresCommand cmd = new IngresCommand(); cmd.Connection = con; cmd.CommandText = "rol_delete"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new IngresParameter("t_id_rol", IngresType.Decimal)); cmd.Parameters["t_id_rol"].Value = int.Parse(this.metroTextBox1.Text); IngresTransaction trans = con.BeginTransaction(); cmd.Transaction = trans; try { cmd.ExecuteNonQuery(); trans.Commit(); MetroMessageBox.Show(this, "Elemento eliminado correctamente.", "Nota", MessageBoxButtons.OK, MessageBoxIcon.Question); } catch (IngresException c) { MetroMessageBox.Show(this, c.ErrorCode + c.Message, "Error"); } con.Close(); this.read(); }
public override void ReaderExecuting( DbCommand command, DbCommandInterceptionContext <DbDataReader> interceptionContext) { int i = 0; int recordsAffected = 0; statements = GetBatchStatements(command.CommandText); if (statements != null) { foreach (String statement in statements) { if (++i >= statements.Count) // break if last { // probably a SELECT command command.CommandText = statement .Replace("__ingres_@@ROWCOUNT", recordsAffected.ToString());; break; } using (IngresCommand command2 = (command as IngresCommand).Clone()) { // probably an INSERT command command2.CommandText = statement; // INSERT/UPDATE/DELETE using the command.Parameters recordsAffected = command2.ExecuteNonQuery(); // clear parms on the SELECT since they were just consumed command.Parameters.Clear(); } } // end foreach (String statement in statements) } base.ReaderExecuting(command, interceptionContext); // SELECT }
/// <summary> /// Connect to two databases while automatically enlisting in the ambient Transaction, /// and execute two non-query SQL commands under the TransactionScope. /// Commit the Transaction by marking the TransactionScope complete, /// if issueScopeComplete argument is set true for testing purposes. /// </summary> /// <param name="connString1">ConnectionString for database 1.</param> /// <param name="connString2">ConnectionString for database 2.</param> /// <param name="commandText1">Non-query CommandText to execute against database 1.</param> /// <param name="commandText2">Non-query CommandText to execute against database 2.</param> /// <param name="issueScopeComplete">If true, issue TransactionScope.Complete()</param> static void ExecuteNonQueryWithinTransactionScope( string connString1, string connString2, string commandText1, string commandText2, bool issueScopeComplete) { Console.WriteLine("\n\tUpdateUsingTransactionScope...\n"); using (TransactionScope scope = new TransactionScope()) { using (IngresConnection conn1 = new IngresConnection(connString1)) { using (IngresConnection conn2 = new IngresConnection(connString2)) { Console.WriteLine("\tIngresConnection1.Open()..."); // Open the connection to the database and // enlist in the ambient Transaction using MSDTC conn1.Open(); Console.WriteLine("\tIngresConnection1.Open() complete\n"); Console.WriteLine("\tIngresConnection2.Open()..."); // Open the connection to the database and // enlist in the ambient Transaction using MSDTC conn2.Open(); Console.WriteLine("\tIngresConnection2.Open() complete\n"); try { IngresCommand cmd1 = conn1.CreateCommand(); cmd1.CommandText = commandText1; cmd1.ExecuteNonQuery(); IngresCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = commandText2; cmd2.ExecuteNonQuery(); // mark the Transaction complete // mark the Transaction complete if (issueScopeComplete) // test debug flag for testing scope.Complete { Console.WriteLine("\tTransactionScope completing..."); scope.Complete(); Console.WriteLine("\tTransactionScope complete\n"); } // note: TransactionScope will not be committed until // TransactionScope Dispose() is called. } catch (Exception ex) { string s = ex.ToString(); Console.WriteLine("\n\tApplication throws Exception!! " + s + "\n"); throw; } } // end using (IngresConnection2) // closes and disposes conn2 } // end using (IngresConnection1) // closes and disposes conn1 Console.WriteLine("\tTransactionScope.Dispose()..."); } // end using (TransactionScope) // calls System.Transactions.Dispose() --> System.Transactions.CommittableTransaction.Commit Console.WriteLine("\tTransactionScope.Dispose() complete\n"); } // end ExecuteNonQueryWithinTransactionScope
} // end ExecuteNonQueryWithinExplicitTransactionScope /// <summary> /// Open a database and execute a non-query SQL string. /// </summary> /// <param name="connString"></param> /// <param name="commandText"></param> static void ExecuteNonQuery( string connString, string commandText) { using (IngresConnection conn = new IngresConnection(connString)) { conn.Open(); IngresCommand cmd = conn.CreateCommand(); cmd.CommandText = commandText; cmd.ExecuteNonQuery(); } // end using (IngresConnection conn) } // end ExecuteNonQuery
private void Update_Click(object sender, EventArgs e) { IngresConnection con = new IngresConnection(Login.myConnectionString); con.Open(); IngresCommand cmd = new IngresCommand(); cmd.Connection = con; cmd.CommandText = "empleado_update"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new IngresParameter("t_id_empleado", IngresType.Decimal)); cmd.Parameters.Add(new IngresParameter("t_primer_nombre", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_segundo_nombre", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_primer_apellido", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_segundo_apellido", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_calle", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_avenida", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_num_casa", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_ciudad", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_departamento", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_referencia", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_correo_primario", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_correo_secundario", IngresType.VarChar)); cmd.Parameters.Add(new IngresParameter("t_fecha_nacimiento", IngresType.Date)); cmd.Parameters.Add(new IngresParameter("t_fecha_inicio", IngresType.Date)); cmd.Parameters["t_id_empleado"].Value = int.Parse(this.id.Text); cmd.Parameters["t_primer_nombre"].Value = this.prinom.Text; cmd.Parameters["t_segundo_nombre"].Value = this.senom.Text; cmd.Parameters["t_primer_apellido"].Value = this.priape.Text; cmd.Parameters["t_segundo_apellido"].Value = this.seape.Text; cmd.Parameters["t_calle"].Value = this.ca.Text; cmd.Parameters["t_avenida"].Value = this.avenida.Text; cmd.Parameters["t_num_casa"].Value = this.numcasa.Text; cmd.Parameters["t_ciudad"].Value = this.ciudad.Text; cmd.Parameters["t_departamento"].Value = this.departamento.Text; cmd.Parameters["t_referencia"].Value = this.referencia.Text; cmd.Parameters["t_correo_primario"].Value = this.pricorreo.Text; cmd.Parameters["t_correo_secundario"].Value = this.secorreo.Text; cmd.Parameters["t_fecha_nacimiento"].Value = this.metroDateTime1.Value.ToString("yyyy-MM-dd"); cmd.Parameters["t_fecha_inicio"].Value = this.metroDateTime2.Value.ToString("yyyy-MM-dd"); try { cmd.ExecuteNonQuery(); MetroMessageBox.Show(this, "Elemento actualizado correctamente.", "Nota", MessageBoxButtons.OK, MessageBoxIcon.Question); } catch (IngresException c) { MetroMessageBox.Show(this, c.ErrorCode + c.Message, "Error"); } con.Close(); this.read(); }
/// <summary> /// Creates a role in the database. /// </summary> /// <param name="roleName">The rolename to create.</param> /// <param name="roleid">The role id.</param> /// <param name="conn">The Ingres connection to use.</param> /// <param name="tran">The Ingres transaction to use.</param> private void CreateRole(string roleName, out string roleid, IngresConnection conn, IngresTransaction tran) { // Validate the roleName ValidationUtil.CheckParameterIsOK(ref roleName, true, true, true, 256, "roleName"); // Ensure that the proposed roleName does not already exist if (this.RoleExists(roleName)) { throw new ProviderException(string.Format(Messages.RoleAlreadyExists, roleName)); } string sql = @" INSERT INTO aspnet_Roles (ApplicationId, RoleId, RoleName, LoweredRoleName, Description) VALUES (?, ?, ?, ?, NULL) "; // Create the command with the current connection and enrol in the transaction IngresCommand cmd = new IngresCommand(sql, this.conn); cmd.Transaction = this.tran; cmd.CommandTimeout = this.config.CommandTimeout; // Generate a new role Id - this will be the sent out roleid = Guid.NewGuid().ToString().ToLower(); // Add the required parameters cmd.Parameters.Add("ApplicationId", DbType.String).Value = this.ApplicationId; cmd.Parameters.Add("RoleId", DbType.String).Value = roleid; cmd.Parameters.Add("RoleName", DbType.String).Value = roleName; cmd.Parameters.Add("LoweredRoleName", DbType.String).Value = roleName.ToLower(); // Execute the query int rows = cmd.ExecuteNonQuery(); // Validate that the query affected the correct numbber of rows. if (rows != 1) { throw new ProviderException(string.Format(Messages.UnknownError)); } }
/// <summary> /// Helper method to create a user. /// </summary> /// <param name="username">The username that we wish to create.</param> /// <returns>The Id for the newly created user.</returns> private string CreateUser(string username) { // Validate the username ValidationUtil.CheckParameterIsOK(ref username, true, true, true, 256, "username"); string id = Guid.NewGuid().ToString().ToLower(); string sql = @" INSERT INTO aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, MobileAlias, IsAnonymous, LastActivityDate) VALUES (?, ?, ?, ?, NULL, '0', ?) "; IngresCommand cmd = new IngresCommand(sql, this.conn); cmd.Parameters.Add("ApplicationId", DbType.String).Value = this.ApplicationId.ToLower(); cmd.Parameters.Add("UserId", DbType.String).Value = id; cmd.Parameters.Add("UserName", DbType.String).Value = username; cmd.Parameters.Add("LoweredUserName", DbType.String).Value = username.ToLower(); cmd.Parameters.Add("LastActivity", DbType.Date).Value = DateTime.Now; int rows = cmd.ExecuteNonQuery(); if (rows != 1) { throw new ProviderException(string.Format(Messages.UnknownError)); } // the user has been successfully created and so we return the id. return(id); }
static void TestDbProc(string connstring, Type type) { int recsaffected; string strSeq; string strName; IngresConnection conn = new IngresConnection(connstring); IngresCommand cmd; Console.WriteLine("\nTestDbProc (using " + type.ToString() + ") to database: " + conn.Database); conn.Open(); cmd = new IngresCommand( "declare global temporary table session.tab (seq integer," + "tabname varchar(32), tabowner varchar(32), numpages integer)" + " on commit preserve rows with norecovery", conn); recsaffected = cmd.ExecuteNonQuery(); Console.WriteLine("ExecuteNonQuery(\"declare gtt\") returned " + recsaffected.ToString()); cmd = new IngresCommand( "insert into session.tab (tabname,tabowner,numpages)" + " select table_name,table_owner,number_pages from iitables", conn); recsaffected = cmd.ExecuteNonQuery(); Console.WriteLine("ExecuteNonQuery(\"insert into gtt\") returned " + recsaffected.ToString()); cmd = new IngresCommand( "{ call gttproc(gtt1 = session.tab)}", conn); // "{ call gttproc(session.tab)}", conn); cmd.CommandType = CommandType.Text; recsaffected = cmd.ExecuteNonQuery(); Console.WriteLine("ExecuteNonQuery(\"execute proc\") returned " + recsaffected.ToString()); cmd = new IngresCommand( "select seq,tabname from session.tab", conn); IngresDataReader reader = cmd.ExecuteReader(); Console.Write(reader.GetName(0) + "\t"); Console.Write(reader.GetName(1)); Console.WriteLine(); while (reader.Read()) { strSeq = reader.IsDBNull(0)? "<none>":reader.GetInt32(0).ToString(); strName = reader.IsDBNull(1)? "<none>":reader.GetString(1); Console.WriteLine(strSeq + "\t" + strName); } // end while loop through result set reader.Close(); conn.Close(); }
/// <summary> /// Takes, as input, a list of user names and a list of role names and removes the /// specified users from the specified roles. /// </summary> /// <remarks> /// This is the main implementation for the <c>RemoveUsersFromRoles</c> method of the provider. Please /// see the corresponding method in the Facade, which calls this method, for full documentaion. /// </remarks> /// <param name="usernames">The array of usernames.</param> /// <param name="roleNames">The array of roles.</param> internal void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { // Validate the input parameters ValidationUtil.CheckArrayParameterIsOk(ref roleNames, true, true, true, 256, "roleNames"); ValidationUtil.CheckArrayParameterIsOk(ref usernames, true, true, true, 256, "usernames"); // Instantiate lists to hold the calculated user and role Ids. List <string> userIdsList = new List <string>(); List <string> roleIdsList = new List <string>(); // Ensure that all of the roleNames are valid foreach (string username in usernames) { string userId = this.GetUserIdByName(username); if (userId == null) { throw new ProviderException(string.Format(Messages.UserWasNotFound, username)); } userIdsList.Add(userId); } // Ensure that all of the roleNames are valid foreach (string rolename in roleNames) { string roleId = this.GetRoleIdByName(rolename); if (roleId == null) { throw new ProviderException(string.Format(Messages.RoleNotFound, rolename)); } roleIdsList.Add(roleId); } // Ensure that the users are actually the the roles to begin with! foreach (string username in usernames) { foreach (string rolename in roleNames) { if (!this.IsUserInRole(username, rolename)) { throw new ProviderException(string.Format(Messages.UserAlreadyNotInRole, username, rolename)); } } } // Build up the SQL string string sql = @" DELETE FROM aspnet_UsersInRoles WHERE UserId = ? AND RoleId = ? "; // Create a new command and enrol in the current transaction. IngresCommand cmd = new IngresCommand(sql, this.conn); cmd.Transaction = this.tran; cmd.CommandTimeout = this.config.CommandTimeout; // Add the required parameters IngresParameter userParm = cmd.Parameters.Add("UserId", DbType.String); IngresParameter roleParm = cmd.Parameters.Add("RoleId", DbType.String); // For each user foreach (string userId in userIdsList) { // For each role foreach (string roleId in roleIdsList) { userParm.Value = userId; roleParm.Value = roleId; // Remove the user from the role cmd.ExecuteNonQuery(); } } }
/// <summary> /// Takes, as input, a role name and a Boolean value that indicates whether to throw an /// exception if there are users currently associated with the role, and then deletes the /// specified role. /// </summary> /// <remarks> /// This is the main implementation for the <c>DeleteRole</c> method of the provider. Please /// see the corresponding method in the Facade, which calls this method, for full documentaion. /// </remarks> /// <param name="roleName">The user name that we wish to delete.</param> /// <param name="throwOnPopulatedRole">Whether we should throw an exception if the role /// we wish to delete has any users in the role or not.</param> /// <returns>Whether the role was successfully deleted.</returns> internal bool DeleteRole(string roleName, bool throwOnPopulatedRole) { // Validate the rolename ValidationUtil.CheckParameterIsOK(ref roleName, true, true, true, 256, "roleName"); // The roleName should exist if (!this.RoleExists(roleName)) { throw new ProviderException(string.Format(Messages.RoleNotFound, roleName)); } // If we have to throw errors for a poupulated roll then we must check if there are // any users in the role. if (throwOnPopulatedRole && (this.GetUsersInRole(roleName).Length > 0)) { throw new ProviderException(string.Format(Messages.RoleNotEmpty)); } string sqlDeleteUsersInRoles = @" DELETE FROM aspnet_UsersInRoles WHERE RoleId = ? "; // Create a new command and enrol in the current transactions IngresCommand cmdDeleteUsersInRoles = new IngresCommand(sqlDeleteUsersInRoles, this.conn); cmdDeleteUsersInRoles.Transaction = this.tran; cmdDeleteUsersInRoles.CommandTimeout = this.config.CommandTimeout; // Add the required parameter cmdDeleteUsersInRoles.Parameters.Add("RoleId", DbType.String).Value = this.GetRoleIdByName(roleName); // Delete the users cmdDeleteUsersInRoles.ExecuteNonQuery(); string sqlDeleteRoles = @" DELETE FROM aspnet_Roles WHERE LoweredRolename = ? AND ApplicationId = ? "; // Create a new command and enrol in the current transaction IngresCommand cmdDeleteRoles = new IngresCommand(sqlDeleteRoles, this.conn); cmdDeleteRoles.Transaction = this.tran; cmdDeleteRoles.CommandTimeout = this.config.CommandTimeout; // Add the required paramaters cmdDeleteRoles.Parameters.Add("LoweredRolename", DbType.String).Value = roleName.ToLower(); cmdDeleteRoles.Parameters.Add("ApplicationId", DbType.String).Value = this.ApplicationId; // Finally delete the role int rows = cmdDeleteRoles.ExecuteNonQuery(); // If more than one row was effected then throw an error if (rows != 1) { throw new ProviderException(string.Format(Messages.UnknownError)); } return(true); }
/// <summary> /// Takes, as input, a list of user names and a list of role names and adds the specified /// users to the specified roles. /// </summary> /// <remarks> /// This is the main implementation for the <c>AddUsersToRoles</c> method of the provider. Please /// see the corresponding method in the Facade, which calls this method, for full documentaion. /// </remarks> /// <param name="usernames">A list of user names.</param> /// <param name="roleNames">A list of roles.</param> internal void AddUsersToRoles(string[] usernames, string[] roleNames) { // Note: Most of this validation is also done by the .NET framework - however I will // explicitly do it here also. ValidationUtil.CheckArrayParameterIsOk(ref roleNames, true, true, true, 256, "roleNames"); ValidationUtil.CheckArrayParameterIsOk(ref usernames, true, true, true, 256, "usernames"); // Ensure that all of the roleNames are valid. foreach (string rolename in roleNames) { if (!this.RoleExists(rolename)) { throw new ProviderException(string.Format(Messages.RoleNotFound, rolename)); } } // Ensure that all of the usernames are valid. foreach (string username in usernames) { if (!this.UserExists(username)) { throw new ProviderException(string.Format(Messages.UserWasNotFound, username)); } } // Ensure that all of the users actually are in the roles. foreach (string username in usernames) { foreach (string rolename in roleNames) { if (this.IsUserInRole(username, rolename)) { throw new ProviderException(string.Format(Messages.UserAlreadyInRole, username, rolename)); } } } // Instantiate a string to hold the required SQL string sql = @" INSERT INTO aspnet_UsersInRoles (UserId, RoleId) VALUES (?, ?) "; // Create a new command and enrol in the current transaction IngresCommand cmd = new IngresCommand(sql, this.conn); cmd.Transaction = this.tran; cmd.CommandTimeout = this.config.CommandTimeout; // Add the required parameters IngresParameter userParam = cmd.Parameters.Add("UserId", DbType.String); IngresParameter roleParam = cmd.Parameters.Add("RoleId", DbType.String); // Note: this if a bit "row at a time" style rather than "chunk at a time" // processing - however it makes for easier to read and understand code and // allows for a static parameterized SQL string. If performance is poor then // this could be changed. // for each user foreach (string username in usernames) { // obtain the user id string userId = this.GetUserIdByName(username); // for each rolename foreach (string rolename in roleNames) { // obtain role id string roleId = this.GetRoleIdByName(rolename); userParam.Value = userId; roleParam.Value = roleId; // try to add user to role // The number of rows affected int rows = cmd.ExecuteNonQuery(); // One row should be affected if (rows != 1) { throw new ProviderException(string.Format(Messages.UnknownError)); } } } }
/// <summary> /// Creates an application in the database. /// </summary> /// <param name="name">The name of the application to create.</param> /// <param name="id">The Id of the application to create.</param> private void CreateApplication(string name, out string id) { // Ensure that the proposed rolename is of a valid form and does not already exist if (name.IndexOf(',') > 0) { throw new ArgumentException(Messages.ApplicationNamesCannotContainCommas); } // Build up the command and connection details id = null; string sql = @" SELECT ApplicationId FROM aspnet_Applications WHERE LoweredApplicationName = ? "; IngresCommand cmd = new IngresCommand(sql, this.conn); cmd.Transaction = this.tran; cmd.CommandTimeout = this.config.CommandTimeout; cmd.Parameters.Add("LoweredApplicationName", DbType.String).Value = name.ToLower(); IngresDataReader datareader = cmd.ExecuteReader(); if (datareader != null) { if (datareader.HasRows) { datareader.Read(); id = datareader.GetString(0); datareader.Close(); return; } id = Guid.NewGuid().ToString(); } if (datareader != null) { datareader.Close(); } sql = @" INSERT INTO aspnet_Applications (ApplicationId, ApplicationName, LoweredApplicationName) VALUES (?, ?, ?) "; cmd = new IngresCommand(sql, this.conn); cmd.Transaction = this.tran; cmd.CommandTimeout = this.config.CommandTimeout; cmd.Parameters.Add("ApplicationId", DbType.String).Value = id; cmd.Parameters.Add("ApplicationName", DbType.String).Value = name; cmd.Parameters.Add("LoweredApplicationName", DbType.String).Value = name.ToLower(); cmd.ExecuteNonQuery(); return; }