How can I declare cookie - c#

I am trying to make this code work fine as i can but i couldnt,i am using cookie and i want to rebind my ListView depending on cookie Location but i am getting error message: "Must declare the scalar variable "#Location"."
protected void Sortcarbtn_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("Location");
using (SqlConnection carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
if (cookie != null)
{
string CarSqlST = #"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit,
SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads Where 1=1 AND Category=#CATE AND Country = #Location ";
var Location = Convert.ToString(cookie["Location"]);
var cat = Convert.ToString(Request.QueryString["cat"]);
string condition = "";
if (barndcardrlst.SelectedValue != "")
{
condition += " and Maker='" + barndcardrlst.SelectedValue + "'";
}
if (GearDrDw.SelectedValue != "")
{
condition += " and Gear='" + GearDrDw.SelectedValue + "'";
}
if (carstatedrdolst.SelectedValue != "")
{
condition += " and State='" + carstatedrdolst.SelectedValue + "'";
}
if (citiesdrdolst.SelectedValue != "")
{
condition += " and City='" + citiesdrdolst.SelectedValue + "'";
}
if (CarCondDrDw.SelectedValue != "")
{
condition += " and Condition='" + CarCondDrDw.SelectedValue + "'";
}
if (CarstusDRDL.SelectedValue != "")
{
condition += " and Status='" + CarstusDRDL.SelectedValue + "'";
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
condition += " and AdsPrice BETWEEN " + CarPriceFrmDrDw.SelectedValue + " AND " + CarPriceToDrDw.SelectedValue;
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
condition += " and Year BETWEEN " + CarYearfrmDrDw.SelectedValue + " AND " + CarYeartoDrDw.SelectedValue;
}
DataTable cdt = new DataTable();
carcon.Open();
SqlCommand ccmd = new SqlCommand();
ccmd.Connection = carcon;
ccmd.CommandType = CommandType.Text;
ccmd.Parameters.AddWithValue("#Country", Location);
ccmd.Parameters.AddWithValue("#CATE", cat);
ccmd.CommandText = CarSqlST + condition;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
ad.Fill(cdt);
cateshowlistview.DataSource = cdt;
cateshowlistview.DataBind();
}
}

Change "#Country" in
ccmd.Parameters.AddWithValue("#Country", Location);
to be "#Location"
ccmd.Parameters.AddWithValue("#Location", Location);
you defined the Country in the SQL Statement to be #Location
string CarSqlST = #"SELECT ... AND Category=#CATE AND Country = #Location ";
Update
To prevent SQL Injection hacks and to allow for SQL to reuse the query options all the fileters where you are concat the string together you should just use SQL Parameters. To make it easy I create a parameters dictionary to add to. Then at the end loop through the dictionary to fill in the SQL Parameters. I also switched it to string builder since could be doing a lot of string concats. I didn't test this code because I don't have your objects or tables or connections.
using (var carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString)))
{
if (cookie != null)
{
// Parameters for SQL
var parameters = new Dictionary<string, object>();
// string builder to build up SQL Statement
var CarSqlST = new StringBuilder(
"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit, " +
"SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads " +
"Where Category = #pCATE AND Country = #pLocation ");
parameters.Add("#pCATE", Request.QueryString["cat"].ToString());
parameters.Add("#pLocation", cookie["Location"]);
if (barndcardrlst.SelectedValue != "")
{
CarSqlST.Append(" and Maker= #pMaker");
parameters.Add("#pMaker", barndcardrlst.SelectedValue);
}
if (GearDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Gear= #pGear");
parameters.Add("#pGear", GearDrDw.SelectedValue);
}
if (carstatedrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pState");
parameters.Add("#pState", carstatedrdolst.SelectedValue);
}
if (citiesdrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pCity");
parameters.Add("#pCity", citiesdrdolst.SelectedValue);
}
if (CarCondDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Condition= #pCondition");
parameters.Add("#pCondition", CarCondDrDw.SelectedValue);
}
if (CarstusDRDL.SelectedValue != "")
{
CarSqlST.Append(" and Status= #pStatus");
parameters.Add("#pStatus", CarstusDRDL.SelectedValue);
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and AdsPrice BETWEEN #pLowPrice AND #pHighPrice");
parameters.Add("#pLowPrice", CarPriceFrmDrDw.SelectedValue);
parameters.Add("#pHighPrice", CarPriceToDrDw.SelectedValue);
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and Year BETWEEN #pLowYear AND #pHighYear");
parameters.Add("#pLowYear", CarYearfrmDrDw.SelectedValue);
parameters.Add("#pHighYear", CarYeartoDrDw.SelectedValue);
}
DataTable cdt = new DataTable();
SqlCommand ccmd = carcon.CreateCommand();;
ccmd.CommandType = CommandType.Text;
// Add all the parameters into this command
foreach (var parameter in parameters)
{
ccmd.Parameters.Add(parameter.Key, parameter.Value);
}
// set the command text from string builder
ccmd.CommandText = CarSqlST.ToString();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
}
}
You could have created the command at the top and filled in the sql parameters right away instead of the dictionary but I like the dictionary approach better in case something happens - exception or we need to bail we never created the SQL Command.

Related

RegisterClientScriptBlock issue when setting warning on repeater

I have some scripts that appear when a field is left blank or with a 0 in an asp.net web form. The warnings are triggering correctly, however the submission does not stop when the script appears. The save button continues to saving the item after it send the "please enter option order" warning. So the prompt appears, but the webform continues processing the save request. I think my brackets may be off. I can't seem to find the issue, does anyone see where I am making a mistake? I'm fairly confident it has something to do with my brackets, but I have not used a textbox inside of a repeater to set a warning/scriptblock before, so may be wrong.I need the page to stop processing the save once the "please enter option order" message appears. The page does stop when the "please enter a stem" triggers if that field is blank, hence my belief it's about the bracket location.
protected void saveButton_Click(object sender, EventArgs e)
{
con.Open();
var dtOptionsData = (DataSet)ViewState["dtOption"];
for (var i = 0; i < RptOptions.Items.Count; i++)
{
var tbOptionOrder = (RptOptions.Items[i].FindControl("OptionOrder") as TextBox);
//dtOptionsData.Tables[0].Rows[i]["Option Order"] = tbOptionOrder.Text;
if (tbOptionOrder.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
}
if (tbOptionOrder.Text == "0")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
}
}
if (stemTextBox.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter a Stem');", true);
}
else
try
{
//get revision header id to insert on original item
SqlCommand cmdOriginalHeaderID = new SqlCommand("select distinct item_header_id from item_header where item_id = #item_id", con);
cmdOriginalHeaderID.Parameters.AddWithValue("#item_id", cloneItemID.Text);
var OriginalHeaderID = cmdOriginalHeaderID.ExecuteScalar();
//sql cmd1 is for item header info
SqlCommand cmd1 = new SqlCommand("Update item_header set item_id = #item_id, old_item_id = #old_item_id, item_stem = #item_stem, modified_by = #modified_by, modified_datetime = getdate(), language = #language,solution = #solution, item_status_id = (select distinct s.item_status_id from item_status s left join item_header h on h.item_status_id = s.item_status_id where s.item_status_desc = #status), item_ownership_type_id = (select distinct o.item_ownership_id from item_ownership_type o left join item_header h on o.item_ownership_id = h.item_ownership_type_id where o.item_ownership_desc = #ownership) ,market_segment_id = (select distinct m.market_segment_id from market_segment m left join item_header h on m.market_segment_id = h.market_segment_id where m.market_segment_name = #marketsegment) , mcs_code_id = (select distinct m.mcs_code_id from mcs_code m left join item_header h on m.mcs_code_id = h.mcs_code_id where m.mcs_code = #mcsid), item_type_id = (select distinct t.item_type_id from type_item t left join item_header h on t.item_type_id = h.item_type_id where t.item_type_desc = #typeid)," +
"author_person_id = (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name= #specialist) where item_header_id = #OriginalHeaderID", con);
cmd1.Parameters.AddWithValue("#item_id", newIdTextBox.Text);
cmd1.Parameters.AddWithValue("#item_stem", stemTextBox.Text);
cmd1.Parameters.AddWithValue("#modified_by", createdByTextBox.Text);
cmd1.Parameters.AddWithValue("#old_item_id", oldItemIDTextBox.Text);
cmd1.Parameters.AddWithValue("#language", txtLanguage.Text);
cmd1.Parameters.AddWithValue("#status", itemStatusDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#ownership", ownershipDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#marketsegment", marketDDL.SelectedValue);
cmd1.Parameters.AddWithValue("#mcsid", txtMCSid.Text);
cmd1.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
cmd1.Parameters.AddWithValue("#specialist", authorTextBox.Text);
cmd1.Parameters.AddWithValue("#typeid", ddlType.SelectedValue);
cmd1.Parameters.AddWithValue("#solution", solutionTextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
foreach (RepeaterItem item in RptOptions.Items)
{
var Option = (item.FindControl("Option") as TextBox).Text;
var OptionOrder = (item.FindControl("OptionOrder") as TextBox).Text.Replace("'", "''");
var Key = (item.FindControl("Key") as CheckBox).Checked;
var itemDetailID = (item.FindControl("DetailID") as TextBox).Text;
//var ItemRefID = (item.FindControl("ItemRefID") as TextBox).Text.Replace("'", "''");
var optionsCmd = new SqlCommand("MERGE item_detail AS [target] USING (VALUES(#OriginalHeaderID, #Option, #OptionOrder, #Key, #ItemDetailID)) AS source(sitemheaderid, soption, soptionorder, soptionkey, sItemDetailID) ON [target].item_header_id = source.sItemHeaderID AND [target].item_detail_id = source.sItemDetailID WHEN MATCHED THEN UPDATE SET [target].[option] = source.soption, [target].option_order = source.soptionorder, [target].option_key = source.soptionkey, [target].[weight] = source.soptionkey, [target].modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT(item_header_id, [option], option_order, option_key,[weight], created_datetime) VALUES(source.sItemHeaderID, source.soption, source.soptionorder, source.soptionkey,source.soptionkey, getdate());", con);
optionsCmd.Parameters.AddWithValue("#ItemDetailID", itemDetailID);
optionsCmd.Parameters.AddWithValue("#Option", Option);
optionsCmd.Parameters.AddWithValue("#OptionOrder", OptionOrder);
optionsCmd.Parameters.AddWithValue("#Key", Key);
optionsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
//refsCmd.Parameters.AddWithValue("#ItemRefID", ItemRefID);
optionsCmd.ExecuteNonQuery();
}
var deletedOptions = ViewState["deleteOptions"] as string;
if (!string.IsNullOrEmpty(deletedOptions))
{
var deleteOptionsCmd = new SqlCommand("delete from item_detail where item_detail_id in (" + deletedOptions.Trim(',') + ")", con);
deleteOptionsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptRefs.Items)
{
var referenceid = (item.FindControl("refID") as TextBox).Text.Replace("'", "''");
var pages = (item.FindControl("Pages") as TextBox).Text.Replace("'", "''");
var Verification = (item.FindControl("Verification") as TextBox).Text.Replace("'", "''");
var ItemRefID = (item.FindControl("ItemRefID") as TextBox).Text.Replace("'", "''");
var refsCmd = new SqlCommand("MERGE item_reference AS [target] USING (VALUES(#OriginalHeaderID, #refID, #Pages, #Verification, #ItemRefID)) AS source(sItemHeaderID, sRefID, sPages, sVerification, sItemReferenceID) ON [target].item_header_id = source.sItemHeaderID AND [target].reference_id = source.sRefID AND [target].item_reference_id = source.sItemReferenceID WHEN MATCHED THEN UPDATE SET [target].[pages] = source.sPages, [target].verification = source.sVerification, [target].modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT(item_header_id, reference_id, [pages], verification, created_datetime)VALUES(source.sItemHeaderID, source.sRefID, source.sPages, source.sVerification, getdate());", con);
refsCmd.Parameters.AddWithValue("#refID", referenceid);
refsCmd.Parameters.AddWithValue("#Pages", pages);
refsCmd.Parameters.AddWithValue("#Verification", Verification);
refsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
refsCmd.Parameters.AddWithValue("#ItemRefID", ItemRefID);
refsCmd.ExecuteNonQuery();
}
var deletedRefs = ViewState["deleteRefs"] as string;
if (!string.IsNullOrEmpty(deletedRefs))
{
var deleteRefsCmd = new SqlCommand("delete from item_reference where item_reference_id in (" + deletedRefs.Trim(',') + ")", con);
deleteRefsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptComments.Items)
{
//var commentid = (item.Controls[0] as TextBox).Text;
var comments = (item.FindControl("comments") as TextBox).Text.Replace("'", "''");
var Specialist = (item.FindControl("Specialist") as TextBox).Text.Replace("'", "''");
var ComID = (item.FindControl("ComID") as TextBox).Text.Replace("'", "''");
var commentsCmd = new SqlCommand("MERGE item_comment AS target USING (Values (#ComID)) AS source(sItemCommentID) ON target.item_comment_id = source.sItemCommentID WHEN MATCHED THEN UPDATE SET target.comment = #comments WHEN NOT MATCHED THEN INSERT (item_header_id, comment, specialist_person_id, created_datetime) VALUES(#originalheaderid,#comments,(Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist),getdate());", con);
commentsCmd.Parameters.AddWithValue("#comments", comments);
commentsCmd.Parameters.AddWithValue("#Specialist", Specialist);
commentsCmd.Parameters.AddWithValue("#ComID", ComID);
commentsCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
commentsCmd.ExecuteNonQuery();
}
var deletedComments = ViewState["deleteComments"] as string;
if (!string.IsNullOrEmpty(deletedComments))
{
var deleteCommentsCmd = new SqlCommand("delete from item_comment where item_comment_id in (" + deletedComments.Trim(',') + ")", con);
deleteCommentsCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptEnemy.Items)
{
var enemyID = (item.FindControl("EnemyID") as TextBox).Text.Replace("'", "''");
var enemyHeaderID = (item.FindControl("EnemyHeaderID") as TextBox).Text.Replace("'", "''");
var ItemStem = (item.FindControl("ItemStem") as TextBox).Text.Replace("'", "''");
var Type = (item.FindControl("Type") as TextBox).Text.Replace("'", "''");
var TypeID = (item.FindControl("TypeID") as TextBox).Text.Replace("'", "''");
var SocID = (item.FindControl("SocID") as TextBox).Text.Replace("'", "''");
var enemyCmd = new SqlCommand("MERGE social_order AS target USING (VALUES (#OriginalHeaderID,#SocID, #EnemyHeaderID, #TypeID)) AS source(sItemHeaderID, sSocID, sEnemyItemHeaderID, sSocialOrderTypeID) ON target.item_header_id = source.sItemHeaderID AND target.related_item_header_id = source.sEnemyItemHeaderID WHEN MATCHED THEN UPDATE SET target.social_order_type_id = #TypeID, target.modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT (item_header_id, related_item_header_id, social_order_type_id, created_datetime) VALUES (#OriginalHeaderID, #EnemyHeaderID, #TypeID, GETDATE());", con);
//enemyCmd.Parameters.AddWithValue("#EnemyID", enemyID);
enemyCmd.Parameters.AddWithValue("#EnemyHeaderID", enemyHeaderID);
//enemyCmd.Parameters.AddWithValue("#ItemStem", ItemStem);
//enemyCmd.Parameters.AddWithValue("#Type", Type);
enemyCmd.Parameters.AddWithValue("#TypeID", TypeID);
enemyCmd.Parameters.AddWithValue("#SocID", SocID);
enemyCmd.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
enemyCmd.ExecuteNonQuery();
}
var deletedEnemies = ViewState["deleteEnemies"] as string;
if (!string.IsNullOrEmpty(deletedEnemies))
{
var deleteEnemiesCmd = new SqlCommand("delete from social_order where soc_entry_id in (" + deletedEnemies.Trim(',') + ")", con);
deleteEnemiesCmd.ExecuteNonQuery();
}
foreach (RepeaterItem item in RptExhibits.Items)
{
//var commentid = (item.Controls[0] as TextBox).Text;
var exhibitID = (item.FindControl("exhibitID") as TextBox).Text.Replace("'", "''");
var itemExhibitID = (item.FindControl("ItemExID") as TextBox).Text.Replace("'", "''");
//exhibitentry += "(" + headerid + "," + "'" + exhibitID + "'),";
var CmdExhibits = new SqlCommand("MERGE item_exhibit AS target USING (VALUES (#OriginalHeaderID, #exhibitID, #itemExhibitID)) AS source(sItemHeaderID, sExhibitID, sItemExID) ON target.item_header_id = source.sItemHeaderID AND target.exhibit_id = source.sExhibitID and target.item_exhibit_id = source.sItemExID WHEN NOT MATCHED THEN INSERT (item_header_id, exhibit_id, created_datetime) VALUES (#OriginalHeaderID, #exhibitID, getdate());", con);
CmdExhibits.Parameters.AddWithValue("#exhibitID", exhibitID);
CmdExhibits.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
CmdExhibits.Parameters.AddWithValue("#itemExhibitID", itemExhibitID);
CmdExhibits.ExecuteNonQuery();
}
var deletedExhibits = ViewState["deleteExhibits"] as string;
if (!string.IsNullOrEmpty(deletedExhibits))
{
var deleteExhibitsCMD = new SqlCommand("delete from item_exhibit where item_exhibit_id in (" + deletedExhibits.Trim(',') + ")", con);
deleteExhibitsCMD.ExecuteNonQuery();
}
//string reventry = "";
//var cmdRevs = new SqlCommand("select item_header_id from item_header where item_id = #item_id", con);
//cmdRevs.Parameters.AddWithValue("#item_id", newIdTextBox.Text);
foreach (RepeaterItem item in RptRevision.Items)
{
var Change = (item.FindControl("Change") as TextBox).Text;
var Reason = (item.FindControl("Reason") as TextBox).Text;
var PersonID = (item.FindControl("PersonID") as TextBox).Text;
var Specialist = (item.FindControl("Specialist") as TextBox).Text;
var ItemRevID = (item.FindControl("IrID") as TextBox).Text;
var cmdRevisions = new SqlCommand("MERGE item_revision AS target USING (Values (#ItemRevID)) AS source(sItemRevisionID) ON target.item_revision_id = source.sItemRevisionID WHEN MATCHED THEN UPDATE SET target.change = #change, target.reason = #reason, target.specialist_person_id = (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist) , target.modified_datetime = GETDATE() WHEN NOT MATCHED THEN INSERT (item_header_id, change, reason, specialist_person_id, created_datetime) VALUES(#OriginalHeaderID, #Change, #Reason, (Select person_id from [persons] p where p.first_Name +' ' + p.last_Name = #Specialist),getdate());", con);
cmdRevisions.Parameters.AddWithValue("#Change", Change);
cmdRevisions.Parameters.AddWithValue("#Reason", Reason);
cmdRevisions.Parameters.AddWithValue("#PersonID", PersonID);
cmdRevisions.Parameters.AddWithValue("#Specialist", Specialist);
cmdRevisions.Parameters.AddWithValue("#OriginalHeaderID", OriginalHeaderID);
cmdRevisions.Parameters.AddWithValue("#ItemRevID", ItemRevID);
cmdRevisions.ExecuteNonQuery();
//reventry += "(" + headerid + "," + "'" + Change + "'," + "'" + Reason + "'," + "" + PersonID + "),";
}
var deletedRevisions = ViewState["deleteRevisions"] as string;
if (!string.IsNullOrEmpty(deletedRevisions))
{
var deleteRevisionsCmd = new SqlCommand("delete from item_revision where item_revision_id in (" + deletedRevisions.Trim(',') + ")", con);
deleteRevisionsCmd.ExecuteNonQuery();
}
//confirmation message and clear form after hitting save.
string msgstring = "You Have Successfully Edited this item";
string content = "window.onload=function(){ alert('";
content += msgstring;
content += "');";
content += "window.location='";
content += Request.Url.AbsoluteUri;
content += "';}";
ClientScript.RegisterStartupScript(this.GetType(), "SucessMessage", content, true);
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", "alert('" + ex.Message.Replace("'", "") + "'); ", true);
}
finally
{
con.Close();
}
}
So I figured out a way to get this to work, adding the answer in case anyone else ever encounters a similar issue.
var dtOptionsData = (DataSet)ViewState["dtOption"];
for (var i = 0; i < RptOptions.Items.Count; i++)
{
var tbOptionOrder = (RptOptions.Items[i].FindControl("OptionOrder") as TextBox);
dtOptionsData.Tables[0].Rows[i]["Option Order"] = tbOptionOrder.Text;
if (tbOptionOrder.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
return;
}
if (tbOptionOrder.Text == "0")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter Option Order');", true);
return;
}
}
if (stemTextBox.Text == "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please Enter a Stem');", true);
return;
}
try

Insert / Send RefNbr to another database in Acumatica ERP System

I have created a payment in Checks and Payments screen of Acumatica screen and released it. Please refer to the following screenshot.
I've already create the following code to provide it.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
}
I already tried to debug this code, but didn't work. And then I try to use this follwing code.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
The codes above is worked, I just remove the if condition (if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{}).
But it's not my goal, I have to filter document only for Doc Status = 'printed' from the document, and this process will be executed when 'Release' button was clicked.
And also any idea how to get all records in APAdjust of the current document ? because I need to comparing adjgrefnbr in apadjust with refnbr in APInvoice based on adjgrefnbr (apadjust) = refnbr (apinvoice). So I can get also all records of APinvoice based on refnbr (APinvoice) = ajgrefnbr (current apadjust). This condition is used to make 'where' condition of query not have to be hardcoded, I will used variable to provide it.
any suggestions to sove this problem ?
Below is an example showing how to extend Release process for checks and subscribe to RowPersisted handler for the APRegister DAC to save released document RefNbr to another database:
public class APPaymentEntryExt : PXGraphExtension<APPaymentEntry>
{
public PXAction<APPayment> release;
[PXUIField(DisplayName = "Release", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Update)]
[PXProcessButton]
public IEnumerable Release(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
return Base.release.Press(adapter);
}
}
public class APReleaseChecksExt : PXGraphExtension<APReleaseChecks>
{
protected virtual void ReleaseChecksFilter_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
var row = e.Row as ReleaseChecksFilter;
if (row == null) return;
Base.APPaymentList.SetProcessDelegate(list =>
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
APReleaseChecks.ReleasePayments(list, row.Action);
});
}
}
By executing quite simple BQL query you can access APAdjust records associated with released check within handler for the RowPersisted event:
public static class APReleaseCheckProcess
{
public static void APPaymentRowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
if (e.TranStatus == PXTranStatus.Completed && e.Operation == PXDBOperation.Update)
{
var doc = e.Row as APPayment;
if (doc != null && doc.Released == true)
{
// save RefNbr to another database
foreach (APAdjust oldadj in PXSelect<APAdjust,
Where<
APAdjust.adjgDocType, Equal<Required<APPayment.docType>>,
And<APAdjust.adjgRefNbr, Equal<Required<APPayment.refNbr>>,
And<APAdjust.adjNbr, Less<Required<APPayment.lineCntr>>>>>>
.Select(sender.Graph, doc.DocType, doc.RefNbr, doc.LineCntr))
{
}
}
}
}
}

fetch data from two different tables on same textbox changed event

I want to fetch some data from two different tables PRO and OPN_STK , in some controls like textboxs and datagridview . when i am selecting data from one table i.e. PRO ,the code is working perfect but when i applied same code just next to it , in same event for fetching data from another table i.e. OPN_STK it throws exception "object refrence not set to an instance of object" . I tried to know about the problem but now I'm blank , this is what I did ,
private void comboProname_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
//if (get == false) //in case when i need to apply condition which I dont prefer
{
string _sql = "select DISTINCT P_batchno,P_sh from PRO where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
//else if (get == true) // opnstk
{
string _sql = "select DISTINCT P_batchno,P_sh from OPN_STK where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
getdata();
}
private void comboBthNo_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
// if (get == false)
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from PRO where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
// else if (get == true) ///// opn stk ///////
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from OPN_STK where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows) // I get exception here only on dt
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
getdata();
}
i would appriciate any help ,thanks in advance .
Put a breakpoint in your code, debug and check that OPN_STK is not null. If it is null that would be your problem.

Format Exception error

I have a function like this
///
/// This function binds the emplist drop down for mentor user.
///
private void BindEmpDropDownForMentor()
{
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
OleDbConnection oleConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand oleCommand = new OleDbCommand(strSelectMentorQuery, oleConnection);
try
{
//Open Connection
oleConnection.Open();
//Set Datasource and close connection
cmbempList.DataSource = oleCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
cmbempList.DataValueField = "";
cmbempList.DataTextField = "NAME";
//Bind the Dropdown
cmbempList.DataBind();
//Add a new item 'ALL TEAM MEMBERS' to the member list
cmbempList.Items.Insert(0, new ListItem("ALL TEAM MEMBERS", "0"));
cmbempList.SelectedIndex = 0;
GridViewDataShowBy = cmbempList.SelectedValue;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
// Close the connection when done with it.
oleConnection.Close();
}
}
But on selected change event of cmbempList, format exception error is being caught saying this that input string was not in correct form in the bold line below
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
gvLeaveList.CurrentPageIndex = 0;
dgDaysAbsent.CurrentPageIndex = 0;
**if (!(Convert.ToInt32(cmbempList.SelectedValue) > 0))
{**
if (this.Session["RoleID"].ToString() == "1")
{
cmbLeads.ClearSelection();
cmbLeads.SelectedIndex = cmbLeads.Items.IndexOf(cmbLeads.Items.FindByValue(this.Session["UserID"].ToString()));
}
}
GridViewDataShowBy = cmbempList.SelectedValue.ToString();
if (cmbempList.SelectedValue != "0" && cmbempList.SelectedValue != "")
{
Page.Title = cmbempList.SelectedItem.Text + " | Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
else
{
Page.Title = "Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
PopulateLeaveList(GridViewDataShowBy, "0");
BindLeaveListGrid(GridViewDataShowBy, cmbLeads.SelectedValue.ToString());
}
It is because cmbempList's DataValueField is being set to an empty string in the BindEmpDropDownForMentor method.
cmbempList.DataValueField = "";
This will cause cmbempList's values to be bound to the values in the DataTextField which are strings. When the SelectedIndexChange event is called it tries to parse the strings to an Int32 which is throwing the exception.
Convert.ToInt32(cmbempList.SelectedValue) > 0
To fix it you can add an aliased ID field in the SQL query and set the cmbempList.DataValueField to that ID name which is probably your intent.
For example in BindEmpDropDownForMentor make this edit to your query:
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME, MLL.LED_ID AS ID FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
And assign your DataValueField to this:
cmbempList.DataValueField = "ID";
try this.
if it still fails look in the debugger what value cmbempList.SelectedValue contains.
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
// ...
object selectedValue = cmbempList.SelectedValue;
if ((selectedValue != null) && (selectedValue != DBNull.Value) && (!(Convert.ToInt32(selectedValue) > 0))
{
// ...

Sending changes from multiple tables in disconnected dataset to SQLServer

We have a third party application that accept calls using an XML RPC mechanism for calling stored procs.
We send a ZIP-compressed dataset containing multiple tables with a bunch of update/delete/insert using this mechanism. On the other end, a CLR sproc decompress the data and gets the dataset.
Then, the following code gets executed:
using (var conn = new SqlConnection("context connection=true"))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
try
{
foreach (DataTable table in ds.Tables)
{
string columnList = "";
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 0)
columnList = table.Columns[0].ColumnName;
else
columnList += "," + table.Columns[i].ColumnName;
}
var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn);
var builder = new SqlCommandBuilder(da);
builder.ConflictOption = ConflictOption.OverwriteChanges;
da.RowUpdating += onUpdatingRow;
da.Update(ds, table.TableName);
}
}
catch (....)
{
.....
}
}
Here's the event handler for the RowUpdating event:
public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e)
{
if ((e.StatementType == StatementType.Update) && (e.Command == null))
{
e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter);
e.Status = UpdateStatus.Continue;
}
}
and the CreateUpdateCommand method:
private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da)
{
string whereClause = "";
string setClause = "";
SqlConnection conn = da.SelectCommand.Connection;
for (int i = 0; i < row.Table.Columns.Count; i++)
{
char quoted;
if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) ||
(row.Table.Columns[i].DataType == Type.GetType("System.DateTime")))
quoted = '\'';
else
quoted = ' ';
string val = row[i].ToString();
if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean"))
val = (bool)row[i] ? "1" : "0";
bool isPrimaryKey = false;
for (int j = 0; j < row.Table.PrimaryKey.Length; j++)
{
if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName)
{
if (whereClause != "")
whereClause += " AND ";
if (row[i] == DBNull.Value)
whereClause += row.Table.Columns[i].ColumnName + "=NULL";
else
whereClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
isPrimaryKey = true;
break;
}
}
/* Only values for column that is not a primary key can be modified */
if (!isPrimaryKey)
{
if (setClause != "")
setClause += ", ";
if (row[i] == DBNull.Value)
setClause += row.Table.Columns[i].ColumnName + "=NULL";
else
setClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
}
}
return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn);
}
However, this is really slow when we have a lot of records.
Is there a way to optimize this or an entirely different way to send lots of udpate/delete on several tables? I would really much like to use TSQL for this but can't figure a way to send a dataset to a regular sproc.
Additional notes:
We cannot directly access the SQLServer database.
We tried without compression and it was slower.
If you're using SQL Server 2008, you should look into MERGE
Look here for more info on MERGE

Categories