Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have button click event, and the values returned from the method should be saved.How can I achieve this?

The button will be clicked multiple times, I have to save the the return value each time the button is clicked
C#
protected void AddRowToAddressee_Click(object sender, EventArgs e)
{
  try
  {
    string var = GenerateInsertSqlToAddressee();
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}


What I have tried:

C#
//public class FrmKeys
//{
// public string savess { get; set; }
// //added below from potential fixes 

// //public static implicit operator FrmKeys(string v)
// //{
// // throw new NotImplementedException();
// //}

// //public void FrmKeys(string v)
// //{
// // //throw new NotImplementedException();
// //}
//}
//protected void AddNewFormKeys_Click(object sender, EventArgs e)
//{
// try
// {
// string savess = GenerateInsertSql2();

// FrmKeys frm = new FrmKeys();

// //FrmKeys InsrtAddFrmKeys = savess;

// //frm = GenerateInsertSql2();

// frm = savess;

// List<frmkeys> FormKeys = new List<frmkeys>();

// FormKeys.Add(frm);

// foreach (FrmKeys k in FormKeys)

// {
// Console.WriteLine(k);

// }

// }

// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }

//}


UPDATE: Adding in GenerateSqlToAddressee() from Comments
C#
public string GenerateInsertSqlToAddressee() {
			string InsertSqlToAddressee = ""; //"not all code paths return a value on GenerateInsertSql()"

			try {

				//Data for ToAddressee TABLE

				string AddrTo_FORM_CODE = FormCodetxt.Text.ToUpper();
				int AddrTo_VERSION = Convert.ToInt32(FormVersiontxt.Text);
				string AddrTo_AddrCode = ddlAddresseecode.SelectedValue;

				int AddrTo_CREATED_BY = Convert.ToInt32(Createdbytxt.Text);

				DateTime dateOnly2 = DateTime.Parse(CreatedDttxt.Text).Date;
				DateTime timeOnly = DateTime.Now;
				DateTime AddrTo_CREATEDDT = dateOnly2.Date.Add(timeOnly.TimeOfDay);

				string AddrTo_Main;

				if (ChBMain.Checked) {

					AddrTo_Main = "T";

				}
				else {

					AddrTo_Main = "F";
				}


				InsertSqlToAddressee = "INSERT INTO EFILE.FORM_ADDRESSEE_TO (form_code, version, addressee_code, main, created_dt,created_by)" +
				" VALUES ('" + AddrTo_FORM_CODE + "'," + AddrTo_VERSION + ",'" + AddrTo_AddrCode + "'" + ",'" + AddrTo_Main
				+ "',TO_DATE('" + AddrTo_CREATEDDT + "', 'mm/dd/yyyy hh:mi:ss AM'),'" + AddrTo_CREATED_BY + "'); ";

			}


			catch (Exception ex) {
				Console.WriteLine(ex.Message);
			}

			return InsertSqlToAddressee; //"not all code paths return a value on GenerateInsertSql()"

		}
Posted
Updated 30-Jul-19 6:03am
v3
Comments
MadMyche 29-Jul-19 16:59pm    
You are going to need to add to your question- things such as what exactly you want to save and where. Right now you are calling some method related to SQL but without seeing the method have no clue if you want to save a text file or want to execute a command.
F-ES Sitecore 30-Jul-19 6:36am    
Saved where?
Member 13285619 30-Jul-19 7:54am    
Below is the method definition.I am thinking to save the return value from the below method in the variable each time the button is clicked.Please let me know if its not clear.

public string GenerateInsertSqlToAddressee()

{
string InsertSqlToAddressee = ""; //“not all code paths return a value on GenerateInsertSql()”

try
{

//Data for ToAddressee TABLE

string AddrTo_FORM_CODE = FormCodetxt.Text.ToUpper();
int AddrTo_VERSION = Convert.ToInt32(FormVersiontxt.Text);
string AddrTo_AddrCode = ddlAddresseecode.SelectedValue;

int AddrTo_CREATED_BY = Convert.ToInt32(Createdbytxt.Text);

DateTime dateOnly2 = DateTime.Parse(CreatedDttxt.Text).Date;
DateTime timeOnly = DateTime.Now;
DateTime AddrTo_CREATEDDT = dateOnly2.Date.Add(timeOnly.TimeOfDay);

string AddrTo_Main;

if (ChBMain.Checked)
{

AddrTo_Main = "T";

}
else
{

AddrTo_Main = "F";
}


InsertSqlToAddressee = "INSERT INTO EFILE.FORM_ADDRESSEE_TO (form_code, version, addressee_code, main, created_dt,created_by)" +
" VALUES ('" + AddrTo_FORM_CODE + "'," + AddrTo_VERSION + ",'" + AddrTo_AddrCode + "'" + ",'" + AddrTo_Main
+ "',TO_DATE('" + AddrTo_CREATEDDT + "', 'mm/dd/yyyy hh:mi:ss AM'),'" + AddrTo_CREATED_BY + "'); ";

}


catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return InsertSqlToAddressee; //“not all code paths return a value on GenerateInsertSql()”






}
Richard Deeming 30-Jul-19 10:26am    
Member 13285619 30-Jul-19 10:41am    
Will check that.Than You!

Here's one approach to fix the SQL Injection vulnerability in your code. Start with a couple of helper classes:
C#
public sealed class CommandParameter
{
    public CommandParameter(string name, object value)
    {
        Name = name;
        Value = value;
    }
    
    public string Name { get; }
    public object Value { get; }
}

public sealed class CommandDefinition
{
    public CommandDefinition(string commandText, CommandType commandType, params CommandParameter[] parameters)
    {
        CommandText = commandText;
        CommandType = commandType;
        Parameters = parameters;
    }
    
    public string CommandText { get; }
    public CommandType CommandType { get; }
    public IReadOnlyList<CommandParameter> Parameters { get; }
    
    public IDbCommand ToCommand(IDbTransaction transaction)
    {
        var command = transaction.Connection.CreateCommand();
        command.Transaction = transaction;
        command.CommandText = CommandText;
        command.CommandType = CommandType;
        
        foreach (CommandParameter parameter in Parameters)
        {
            IDbDataParameter p = command.CreateParameter();
            p.ParameterName = parameter.Name;
            p.Value = parameter.Value;
            command.Parameters.Add(p);
        }
        
        return command;
    }
}
Then change your GenerateInsertSqlToAddressee method to return an instance of the new CommandDefinition class, and change your list to store instances of that class:
C#
private List<CommandDefinition> savedCommands = new List<CommandDefinition>();

protected void AddRowToAddressee_Click(object sender, EventArgs e)
{
    try
    {
        CommandDefinition cmd = GenerateInsertSqlToAddressee();
        if (cmd != null) savedCommands.Add(cmd);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

public CommandDefinition GenerateInsertSqlToAddressee() 
{
    try 
    {
        string AddrTo_FORM_CODE = FormCodetxt.Text.ToUpper();
        int AddrTo_VERSION = Convert.ToInt32(FormVersiontxt.Text);
        string AddrTo_AddrCode = ddlAddresseecode.SelectedValue;

        int AddrTo_CREATED_BY = Convert.ToInt32(Createdbytxt.Text);

        DateTime dateOnly2 = DateTime.Parse(CreatedDttxt.Text).Date;
        DateTime timeOnly = DateTime.Now;
        DateTime AddrTo_CREATEDDT = dateOnly2.Date.Add(timeOnly.TimeOfDay);

        string AddrTo_Main = ChBMain.Checked ? "T" : "F";
        
        return new CommandDefinition(
            @"INSERT INTO EFILE.FORM_ADDRESSEE_TO (form_code, version, addressee_code, main, created_dt, created_by)
              VALUES (@form_code, @version, @addressee_code, @main, @created_dt, @created_by)",
            CommandType.Text,
            new CommandParameter("@form_code", AddrTo_FORM_CODE),
            new CommandParameter("@version", AddrTo_VERSION),
            new CommandParameter("@addressee_code", AddrTo_AddrCode),
            new CommandParameter("@main", AddrTo_Main),
            new CommandParameter("@created_dt", AddrTo_CREATEDDT),
            new CommandParameter("@created_by", AddrTo_CREATED_BY)
        );
    }
    catch (Exception ex) 
    {
        Console.WriteLine(ex.Message);
        return null;
    }
}
Then, when you need to execute the commands:
C#
using (SqlConnection connection = new SqlConnection("..."))
{
    connection.Open();
    
    using (SqlTransaction transaction = connection.BeginTransaction())
    {
        foreach (CommandDefinition commandDefinition in savedCommands)
        {
            using (IDbCommand command = commandDefinition.ToCommand(transaction))
            {
                command.ExecuteNonQuery();
            }
        }
        
        transaction.Commit();
    }
}

EDIT: I notice you've tagged the question as "ASP.NET"; if that's correct, then you won't be able to store the list of commands in a field on your page / controller, since it will be lost between requests. You'd need to look at storing it in session state instead.
 
Share this answer
 
v2
!! NO NO NO !
NEVER EVER build an SQL command by cobbling a bunch of user input into a string- it is the reason why SQL Injection is still in the Top 10 application vulnerabilities 2 decades after it was identified.

The proper way to create commands and place values into them is going to be through Parameters

Update: Little busy so I didn't get the time I wanted for this... This will be a guideline and may have some syntax errors..

Part 1 is going to build up an Address class to define what an address is along with methods to create and save the list
1a. Create an Address class that parallels the data in your database table
C#
public class Addressee {
	string FormCode { get; set; }
	int Version { get; set; }
	string AddresseeCode { get; set; }
	string Main { get; set; }
	DateTime Created { get; set; }
	string CreatedBy { get; set; }

	public Addressee() { }
}




1b. Add an overloaded construct for easy population
C#
public Addressee(string formCode, int version, string addresseecode, string main, DateTime created, string createdBy) {
	FormCode = formCode;
	Version = version;
	AddresseeCode = addresseecode;
	Created = created;
	CreatedBy = createdBy;
}


1c. Add a method to save a address. (I skipped this)
1d. Add a method to save a list of addresses
C#
public void SaveAddressList(List<Addressee> addressees) {
	if ((addressees != null) && (addressees.Count > 0)) {

		string strSqlConnection = "placeholder";
		string Query = "INSERT INTO EFILE.FORM_ADDRESSEE_TO (form_code, version, addressee_code, main, created_dt,created_by) ";
		Query += "VALUES (@form_code, @version, @addressee_code, @main, @created_dt, @created_by";

		using (SqlConnection conn = new SqlConnection(strSqlConnection)) {
			using (SqlCommand cmd = new SqlCommand(Query, conn)) {
				conn.Open();
				foreach (Addressee a in addressees) {
					cmd.Parameters.AddWithValue("@form_code", a.FormCode);
					cmd.Parameters.AddWithValue("@addressee_code", a.AddresseeCode);
					cmd.Parameters.AddWithValue("@version", a.Version);
					cmd.Parameters.AddWithValue("@main", a.Main);
					cmd.Parameters.AddWithValue("@created_dt", a.CreatedDt);
					cmd.Parameters.AddWithValue("@created_by", a.CreatedBy);

					cmd.ExecuteNonQuery();

					cmd.Parameters.Clear();
				}
				conn.Close();
			}
		}
	}
}


The second part is going to be modifications to the form and code behind calling this class
2a. Add a List of addresses to the class
2b. Populate the list in your existing routine
2c. Call the "save" method whenever you get that far.
C#
private List<addressee> AddressList = new List<addressee>();

protected void AddRowToAddressee_Click(object sender, EventArgs e) {
	if ((Address == null) ||(AddressList == null)) { Address = new Addressee(); AddressList = new List<addressee>(); }
	try {
		//string var = GenerateInsertSqlToAddressee();
		AddressList.Add(GetAddress());
	}
	catch (Exception ex) {
		Console.WriteLine(ex.Message);
	}
}

protected void SaveAddressListRows(object sender, EventArgs e) {
	Address.SaveAddressList(AddressList);
}
 
Share this answer
 
v2
C#
// Class level.
protected List<string> saved = new List<string>;
...
...
string var = GenerateInsertSqlToAddressee();
saved.Add( var );
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900