i want to add a new value in access but when i run this it inserts the last viewed data [duplicate] - asp.net

I have a webpage that has a web form on it. The form is pre-populated with data from a SQL Server database. The user can go in and edit any of the fields and click the "Save" button on the bottom to update the record in the database. For some reason, the update statement isnt updating the record in the database when I have the form pre-filled with data. If I remove the code pre-filling the form on the page load method the update statement works as it should. When I have the form pre-filled with data in the page load method, the update statement appears to be updating the record with the same data that it already had in it, not the new information the user entered. I am completely lost on how to fix this issue as the form has to have data preloaded in it so the user can edit the form respectively.
Can someone point out an error or some correction that I need to make? I've hit the proverbially brick wall :(
Below you will find the page load method and the save button click event handler.
protected void Page_Load(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
SqlCommand selectCommand = new SqlCommand(selectStatement, connection1);
connection1.Open();
using (SqlDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
UMTextBox.Text = reader["make"].ToString();
UMOTextBox.Text = reader["model"].ToString();
UTTextBox.Text = reader["type"].ToString();
USITextBox.Text = reader["size"].ToString();
USTextBox.Text = reader["serial"].ToString();
UATextBox.Text = reader["arrangement"].ToString();
UCTextBox.Text = reader["class"].ToString();
UDTextBox.Text = reader["discharge"].ToString();
UMSTextBox.Text = reader["make_sheave"].ToString();
USDTextBox.Text = reader["sheave_diameter"].ToString();
USBTextBox.Text = reader["sheave_bore"].ToString();
UBNTextBox.Text = reader["belts"].ToString();
UBSTextBox.Text = reader["belt_size"].ToString();
UFNTextBox.Text = reader["filters"].ToString();
UFSTextBox.Text = reader["filter_size"].ToString();
TCFMDTextBox.Text = reader["unitTotalCFMDesign"].ToString();
TCFMATextBox.Text = reader["unitTotalCFMActual"].ToString();
RACFMDTextBox.Text = reader["unitReturnAirCFMDesign"].ToString();
RACFMATextBox.Text = reader["unitReturnAirCFMActual"].ToString();
OACFMDTextBox.Text = reader["unitOutsideAirCFMDesign"].ToString();
OACFMATextBox.Text = reader["unitOutsideAirCFMActual"].ToString();
EACFMDTextBox.Text = reader["unitExhaustAirCFMDesign"].ToString();
EACFMATextBox.Text = reader["unitExhaustAirCFMActual"].ToString();
FRPMDTextBox.Text = reader["unitFanRPMDesign"].ToString();
FRPMATextBox.Text = reader["unitFanRPMActual"].ToString();
MRPMDTextBox.Text = reader["unitMotorRPMDesign"].ToString();
MRPMATextBox.Text = reader["unitMotorRPMActual"].ToString();
MVDTextBox.Text = reader["unitMotorVoltsDesign"].ToString();
MVATextBox.Text = reader["unitMotorVoltsActual"].ToString();
MADTextBox.Text = reader["unitMotorAmpsDesign"].ToString();
MAATextBox.Text = reader["unitMotorAmpsActual"].ToString();
MMTextBox.Text = reader["motor_make"].ToString();
MFTextBox.Text = reader["motor_frame"].ToString();
MHPTextBox.Text = reader["motor_hp"].ToString();
MRPMTextBox.Text = reader["motor_rpm"].ToString();
MVTextBox.Text = reader["motor_volts"].ToString();
MPHTextBox.Text = reader["motor_phasehz"].ToString();
MFLATextBox.Text = reader["motor_fl_amps"].ToString();
MSFTextBox.Text = reader["motor_sf"].ToString();
MMSTextBox.Text = reader["motor_make_sheave"].ToString();
MSDTextBox.Text = reader["motor_sheave_diameter"].ToString();
MSBTextBox.Text = reader["motor_sheave_bore"].ToString();
MODTextBox.Text = reader["motor_operating_diameter"].ToString();
MSCDTextBox.Text = reader["motor_sheave_center_distance"].ToString();
TSPDTextBox.Text = reader["motorTotalSPDesign"].ToString();
TSPATextBox.Text = reader["motorTotalSPActual"].ToString();
ESPDTextBox.Text = reader["motorEnteringSPDesign"].ToString();
ESPATextBox.Text = reader["motorEnteringSPActual"].ToString();
SSPDTextBox.Text = reader["motorSuctionSPDesign"].ToString();
SSPATextBox.Text = reader["motorSuctionSPActual"].ToString();
DSPDTextBox.Text = reader["motorDischargeSPDesign"].ToString();
DSPATextBox.Text = reader["motorDischargeSPActual"].ToString();
PCSPDTextBox.Text = reader["motorPreheatCoilSPDesign"].ToString();
PCSPATextBox.Text = reader["motorPreheatCoilSPActual"].ToString();
CCSPDTextBox.Text = reader["motorCoolingCoilSPDesign"].ToString();
CCSPATextBox.Text = reader["motorCoolingCoilSPActual"].ToString();
RCSPDTextBox.Text = reader["motorReheatCoilSPDesign"].ToString();
RCSPATextBox.Text = reader["motorReheatCoilSPActual"].ToString();
FSPDTextBox.Text = reader["motorFilterSPDesign"].ToString();
FSPATextBox.Text = reader["motorFilterSPActual"].ToString();
AFSPDTextBox.Text = reader["motorAfterFilterSPDesign"].ToString();
AFSPATextBox.Text = reader["motorAfterFilterSPActual"].ToString();
WSPDTextBox.Text = reader["motorWheelSPDesign"].ToString();
WSPATextBox.Text = reader["motorWheelSPActual"].ToString();
RemarksTextArea.Text = reader["remarks"].ToString();
}
}
connection1.Close();
}
}
And here is the Save button click handler that updates the record in the database.
protected void SaveReportButton_Click(object sender, EventArgs e)
{
String projectID = Request.QueryString["jobID"];
String reportID = Request.QueryString["reportID"];
string unitMake = UMTextBox.Text;
string unitModel = UMOTextBox.Text;
string unitType = UTTextBox.Text;
string unitSize = USITextBox.Text;
string unitSerial = USTextBox.Text;
string unitArrangement = UATextBox.Text;
string unitClass = UCTextBox.Text;
string unitDischarge = UDTextBox.Text;
string unitMS = UMSTextBox.Text;
string unitSD = USDTextBox.Text;
string unitSB = USBTextBox.Text;
string unitBeltNumber = UBNTextBox.Text;
string unitBeltSize = UBSTextBox.Text;
string unitFilterNumber = UFNTextBox.Text;
string unitFilterSize = UFSTextBox.Text;
string unitTotalCFMDesign = TCFMDTextBox.Text;
string unitTotalCFMActual = TCFMATextBox.Text;
string unitReturnAirCFMDesign = RACFMDTextBox.Text;
string unitReturnAirCFMActual = RACFMATextBox.Text;
string unitOutsideAirCFMDesign = OACFMDTextBox.Text;
string unitOutsideAirCFMActual = OACFMATextBox.Text;
string unitExhaustAirCFMDesign = EACFMDTextBox.Text;
string unitExhaustAirCFMActual = EACFMATextBox.Text;
string unitFanRPMDesign = FRPMDTextBox.Text;
string unitFanRPMActual = FRPMATextBox.Text;
string unitMotorRPMDesign = MRPMDTextBox.Text;
string unitMotorRPMActual = MRPMATextBox.Text;
string unitMotorVoltsDesign = MVDTextBox.Text;
string unitMotorVoltsActual = MVATextBox.Text;
string unitMotorAmpsDesign = MADTextBox.Text;
string unitMotorAmpsActual = MAATextBox.Text;
string motorMake = MMTextBox.Text;
string motorFrame = MFTextBox.Text;
string motorHP = MHPTextBox.Text;
string motorRPM = MRPMTextBox.Text;
string motorVolts = MVTextBox.Text;
string motorPhaseHz = MPHTextBox.Text;
string motorFullLoadAmps = MFLATextBox.Text;
string motorSF = MSFTextBox.Text;
string motorMakeSheave = MMSTextBox.Text;
string motorSheaveDiameter = MSDTextBox.Text;
string motorSheaveBore = MSBTextBox.Text;
string motorOperatingDiameter = MODTextBox.Text;
string motorSheaveCDistance = MSCDTextBox.Text;
string motorTotalSPDesign = TSPDTextBox.Text;
string motorTotalSPActual = TSPATextBox.Text;
string motorEnteringSPDesign = ESPDTextBox.Text;
string motorEnteringSPActual = ESPATextBox.Text;
string motorSuctionSPDesign = SSPDTextBox.Text;
string motorSuctionSPActual = SSPATextBox.Text;
string motorDischargeSPDesign = DSPDTextBox.Text;
string motorDischargeSPActual = DSPATextBox.Text;
string motorPreheatCoilSPDesign = PCSPDTextBox.Text;
string motorPreheatCoilSPActual = PCSPATextBox.Text;
string motorCoolingCoilSPDesign = CCSPDTextBox.Text;
string motorCoolingCoilSPActual = CCSPATextBox.Text;
string motorReheatCoilSPDesign = RCSPDTextBox.Text;
string motorReheatCoilSPActual = RCSPATextBox.Text;
string motorFilterSPDesign = FSPDTextBox.Text;
string motorFilterSPActual = FSPATextBox.Text;
string motorAfterFilterSPDesign = AFSPDTextBox.Text;
string motorAfterFilterSPActual = AFSPATextBox.Text;
string motorWheelSPDesign = WSPDTextBox.Text;
string motorWheelSPActual = WSPATextBox.Text;
string remarks = RemarksTextArea.Text;
string updateStatement = #"UPDATE ahu_data SET make=#UNITMAKE, model=#UNITMODEL, type=#UNITTYPE, size=#UNITSIZE, serial=#UNITSERIAL, arrangement=#UNITARRANGEMENT,
class=#UNITCLASS, discharge=#UNITDISCHARGE, make_sheave=#UNITMS, sheave_diameter=#UNITSD, sheave_bore=#UNITSB,
belts=#UNITBELTNUMBER, belt_size=#UNITBELTSIZE, filters=#UNITFILTERNUMBER, filter_size=#UNITBELTSIZE,
unitTotalCFMDesign=#UNITTOTALCFMDESIGN, unitTotalCFMActual=#UNITTOTALCFMACTUAL, unitReturnAirCFMDesign=#UNITRETURNAIRCFMDESIGN,
unitReturnAirCFMActual=#UNITRETURNAIRCFMACTUAL, unitOutsideAirCFMDesign=#UNITOUTSIDEAIRCFMDESIGN,
unitOutsideAirCFMActual=#UNITOUTSIDEAIRCFMACTUAL, unitExhaustAirCFMDesign=#UNITEXHAUSTAIRCFMDESIGN,
unitExhaustAirCFMActual=#UNITEXHAUSTAIRCFMACTUAL, unitFanRPMDesign=#UNITFANRPMDESIGN,
unitFanRPMActual=#UNITFANRPMACTUAL, unitMotorRPMDesign=#UNITMOTORRPMDESIGN, unitMotorRPMActual=#UNITMOTORRPMACTUAL,
unitMotorVoltsDesign=#UNITMOTORVOLTSDESIGN, unitMotorVoltsActual=#UNITMOTORVOLTSACTUAL, unitMotorAmpsDesign=#UNITMOTORAMPSDESIGN,
unitMotorAmpsActual=#UNITMOTORAMPSACTUAL, motor_make=#MOTORMAKE, motor_frame=#MOTORFRAME, motor_hp=#MOTORHP,
motor_rpm=#MOTORRPM, motor_volts=#MOTORVOLTS, motor_phasehz=#MOTORPHASEHZ, motor_fl_amps=#MOTORFULLLOADAMPS,
motor_sf=#MOTORSF, motor_make_sheave=#MOTORMAKESHEAVE, motor_sheave_diameter=#MOTORSHEAVEDIAMETER,
motor_sheave_bore=#MOTORSHEAVEBORE, motor_operating_diameter=#MOTOROPERATINGDIAMETER, motor_sheave_center_distance=#MOTORSHEAVECDISTANCE,
motorTotalSPDesign=#MOTORTOTALSPDESIGN, motorTotalSPActual=#MOTORTOTALSPACTUAL, motorEnteringSPDesign=#MOTORENTERINGSPDESIGN,
motorEnteringSPActual=#MOTORENTERINGSPACTUAL, motorSuctionSPDesign=#MOTORSUCTIONSPDESIGN, motorSuctionSPActual=#MOTORSUCTIONSPACTUAL,
motorDischargeSPDesign=#MOTORDISCHARGESPDESIGN, motorDischargeSPActual=#MOTORDISCHARGESPACTUAL, motorPreheatCoilSPDesign=#MOTORPREHEATCOILSPDESIGN,
motorPreheatCoilSPActual=#MOTORPREHEATCOILSPACTUAL, motorCoolingCoilSPDesign=#MOTORCOOLINGCOILSPDESIGN, motorCoolingCoilSPActual=#MOTORCOOLINGCOILSPACTUAL,
motorReheatCoilSPDesign=#MOTORREHEATCOILSPDESIGN, motorReheatCoilSPActual=#MOTORREHEATCOILSPACTUAL, motorFilterSPDesign=#MOTORFILTERSPDESIGN,
motorFilterSPActual=#MOTORFILTERSPACTUAL, motorAfterFilterSPDesign=#MOTORAFTERFILTERSPDESIGN, motorAfterFilterSPActual=#MOTORAFTERFILTERSPACTUAL,
motorWheelSPDesign=#MOTORWHEELSPDESIGN, motorWheelSPActual=#MOTORWHEELSPACTUAL, remarks=#REMARKS WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
connection1.Open();
using (SqlCommand updateCommand = new SqlCommand(updateStatement, connection1))
{
updateCommand.Parameters.AddWithValue("#UNITMAKE", unitMake);
updateCommand.Parameters.AddWithValue("#UNITMODEL", unitModel);
updateCommand.Parameters.AddWithValue("#UNITTYPE", unitType);
updateCommand.Parameters.AddWithValue("#UNITSIZE", unitSize);
updateCommand.Parameters.AddWithValue("#UNITSERIAL", unitSerial);
updateCommand.Parameters.AddWithValue("#UNITARRANGEMENT", unitArrangement);
updateCommand.Parameters.AddWithValue("#UNITCLASS", unitClass);
updateCommand.Parameters.AddWithValue("#UNITDISCHARGE", unitDischarge);
updateCommand.Parameters.AddWithValue("#UNITMS", unitMS);
updateCommand.Parameters.AddWithValue("#UNITSD", unitSD);
updateCommand.Parameters.AddWithValue("#UNITSB", unitSB);
updateCommand.Parameters.AddWithValue("#UNITBELTNUMBER", unitBeltNumber);
updateCommand.Parameters.AddWithValue("#UNITBELTSIZE", unitBeltSize);
updateCommand.Parameters.AddWithValue("#UNITFILTERNUMBER", unitFilterNumber);
updateCommand.Parameters.AddWithValue("#UNITFILTERSIZE", unitFilterSize);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMDESIGN", unitTotalCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITTOTALCFMACTUAL", unitTotalCFMActual);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMDESIGN", unitReturnAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITRETURNAIRCFMACTUAL", unitReturnAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMDESIGN", unitOutsideAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITOUTSIDEAIRCFMACTUAL", unitOutsideAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMDESIGN", unitExhaustAirCFMDesign);
updateCommand.Parameters.AddWithValue("#UNITEXHAUSTAIRCFMACTUAL", unitExhaustAirCFMActual);
updateCommand.Parameters.AddWithValue("#UNITFANRPMDESIGN", unitFanRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITFANRPMACTUAL", unitFanRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMDESIGN", unitMotorRPMDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORRPMACTUAL", unitMotorRPMActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSDESIGN", unitMotorVoltsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORVOLTSACTUAL", unitMotorVoltsActual);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSDESIGN", unitMotorAmpsDesign);
updateCommand.Parameters.AddWithValue("#UNITMOTORAMPSACTUAL", unitMotorAmpsActual);
updateCommand.Parameters.AddWithValue("#MOTORMAKE", motorMake);
updateCommand.Parameters.AddWithValue("#MOTORFRAME", motorFrame);
updateCommand.Parameters.AddWithValue("#MOTORHP", motorHP);
updateCommand.Parameters.AddWithValue("#MOTORRPM", motorRPM);
updateCommand.Parameters.AddWithValue("#MOTORVOLTS", motorVolts);
updateCommand.Parameters.AddWithValue("#MOTORPHASEHZ", motorPhaseHz);
updateCommand.Parameters.AddWithValue("#MOTORFULLLOADAMPS", motorFullLoadAmps);
updateCommand.Parameters.AddWithValue("#MOTORSF", motorSF);
updateCommand.Parameters.AddWithValue("#MOTORMAKESHEAVE", motorMakeSheave);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEDIAMETER", motorSheaveDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVEBORE", motorSheaveBore);
updateCommand.Parameters.AddWithValue("#MOTOROPERATINGDIAMETER", motorOperatingDiameter);
updateCommand.Parameters.AddWithValue("#MOTORSHEAVECDISTANCE", motorSheaveCDistance);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPDESIGN", motorTotalSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORTOTALSPACTUAL", motorTotalSPActual);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPDESIGN", motorEnteringSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORENTERINGSPACTUAL", motorEnteringSPActual);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPDESIGN", motorSuctionSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORSUCTIONSPACTUAL", motorSuctionSPActual);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPDESIGN", motorDischargeSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORDISCHARGESPACTUAL", motorDischargeSPActual);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPDESIGN", motorPreheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORPREHEATCOILSPACTUAL", motorPreheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPDESIGN", motorCoolingCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORCOOLINGCOILSPACTUAL", motorCoolingCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPDESIGN", motorReheatCoilSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORREHEATCOILSPACTUAL", motorReheatCoilSPActual);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPDESIGN", motorFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORFILTERSPACTUAL", motorFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPDESIGN", motorAfterFilterSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORAFTERFILTERSPACTUAL", motorAfterFilterSPActual);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPDESIGN", motorWheelSPDesign);
updateCommand.Parameters.AddWithValue("#MOTORWHEELSPACTUAL", motorWheelSPActual);
updateCommand.Parameters.AddWithValue("#REMARKS", remarks);
updateCommand.ExecuteNonQuery();
}
connection1.Close();
}
}

ASP.NET page lifecycle causes this situation if you don't protect the Page_Load from reexecuting the code that fill your textboxes.
if (!IsPostBack)
{
string selectStatement = "SELECT * FROM ahu_data WHERE unit_ID = " + reportID;
string sqlConnectionString = "Removed for Security";
using (SqlConnection connection1 = new SqlConnection(sqlConnectionString))
{
.... rest of code that pre-fill your fields
Page.IsPostBack is a boolean property of the Page that informs your code if the page is called for the first time or if it is called as a consequence of some event that need to be processed server-side.
In the latter case you should not execute again the code that fills your textboxes otherwise, when the flow reaches your button code, you will find the textboxes with the original values instead of the modified ones because the Page_Load has resetted everything.
And do not forget the comment above about parameterizing your first query. You have already done the biggest part parameterizing the UPDATE, just one parameter remains and it is complete.

The update is working just fine, the problem is that it's using the same data that's already in the table, so it won't change anything.
When you click the save button the page does a postback to run the code on the server. First the Page_Load event runs and loads the original data that will replace the data that you entered in the form. Then the SaveReportButton_Click event runs that updates the record.
To keep the Page_Load event handler from replacing the data in the form, you should use the isPostBack property to check if the page is loaded due to a postback:
if (!IsPostBack) {
// load the data from the database in here
}

Related

Calling Netsuite SOAP .wsdl from C# .Net Core

First of all, I found this link which was a HUGE help to get this working.
https://medium.com/#benwmills/using-the-netsuite-suitetalk-api-with-net-core-net-standard-40f1a4464da1
But wanted to post my findings - in case it helps anyone else.
Step 1: Add a Service Reference to your project (WCF Web Service)
Step 2: Create NetSuitePortTypeClient and Open it (use your own account specific)
NetSuitePortTypeClient nsptc = new NetSuitePortTypeClient(NetSuitePortTypeClient.EndpointConfiguration.NetSuitePort, "https://########.suitetalk.api.netsuite.com/services/NetSuitePort_2021_2");
await nsptc.OpenAsync();
Step 3: Create a Transaction Search in this example
TransactionSearch tranSearch = new TransactionSearch();
TransactionSearchBasic tranSearchBasic = new TransactionSearchBasic();
SearchStringField searchstringfield = new SearchStringField();
searchstringfield.#operator = SearchStringFieldOperator.#is;
searchstringfield.operatorSpecified = true;
searchstringfield.searchValue = "$$$$$$";
tranSearchBasic.tranId = searchstringfield;
tranSearch.basic = tranSearchBasic;
Step 4: Call the Search
searchResponse sresponse = await nsptc.searchAsync(CreateTokenPassport(), null, null, null, tranSearch);
AND Here is the CreateTokenPassword function
public TokenPassport CreateTokenPassport()
{
string account = "account";
string consumerKey = "ckey";
string consumerSecret = "csecret";
string tokenId = "token";
string tokenSecret = "tokensecret";
string nonce = ComputeNonce();
long timestamp = ComputeTimestamp();
TokenPassportSignature signature = ComputeSignature(account, consumerKey, consumerSecret, tokenId, tokenSecret, nonce, timestamp);
TokenPassport tokenPassport = new TokenPassport();
tokenPassport.account = account;
tokenPassport.consumerKey = consumerKey;
tokenPassport.token = tokenId;
tokenPassport.nonce = nonce;
tokenPassport.timestamp = timestamp;
tokenPassport.signature = signature;
return tokenPassport;
}
You've left out the ComputeNonce, ComputeTimestamp, ComputeSignature functions so this code doesn't work...
Here is full code from example of calling NetSuite SOAP using C#:
public TokenPassport CreateTokenPassport()
{
string account = DataCollection["login.acct"];
string consumerKey = DataCollection["login.tbaConsumerKey"];
string consumerSecret = DataCollection["login.tbaConsumerSecret"];
string tokenId = DataCollection["login.tbaTokenId"];
string tokenSecret = DataCollection["login.tbaTokenSecret"];
string nonce = ComputeNonce();
long timestamp = ComputeTimestamp();
TokenPassportSignature signature = ComputeSignature(account, consumerKey, consumerSecret, tokenId, tokenSecret, nonce, timestamp);
TokenPassport tokenPassport = new TokenPassport();
tokenPassport.account = account;
tokenPassport.consumerKey = consumerKey;
tokenPassport.token = tokenId;
tokenPassport.nonce = nonce;
tokenPassport.timestamp = timestamp;
tokenPassport.signature = signature;
return tokenPassport;
}
private string ComputeNonce()
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] data = new byte[20];
rng.GetBytes(data);
int value = Math.Abs(BitConverter.ToInt32(data, 0));
return value.ToString();
}
private long ComputeTimestamp()
{
return ((long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
private TokenPassportSignature ComputeSignature(string compId, string consumerKey, string consumerSecret,
string tokenId, string tokenSecret, string nonce, long timestamp)
{
string baseString = compId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
string key = consumerSecret + "&" + tokenSecret;
string signature = "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyBytes = encoding.GetBytes(key);
byte[] baseStringBytes = encoding.GetBytes(baseString);
using (var hmacSha1 = new HMACSHA1(keyBytes))
{
byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
signature = Convert.ToBase64String(hashBaseString);
}
TokenPassportSignature sign = new TokenPassportSignature();
sign.algorithm = "HMAC-SHA1";
sign.Value = signature;
return sign;
}

upload a Excel file without header in Grid View (already defined column names) in asp .net C#, each time it show error when reaches at dt.Rows.Add()

here the code which i am using to import excel to grid view.. Each time getting error at dt.Rows.Add()
here the error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.Couldn't store in SUPPLY DATE Column. Expected type is DateTime."
in .aspx page i don't defined any column with datetime
DataTable dtExl = conUpLoad.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExl.Rows[0]["Table_Name"].ToString();
OleDbCommand ExcelCommand = new OleDbCommand("Select * From [" + getExcelSheetName + "]", conUpLoad);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);
//conUpLoad.Close();
// Clearing the grid ::::::::::::::::::::::
ViewState["dt"] = null;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
// ::::::::::::::::::::::::::::::::::::::::
DataTable dt = ExcelDataSet.Tables[0];
int i = 0;
if (ExcelDataSet.Tables[0].Rows.Count > 0)
{
String DINumber = ExcelDataSet.Tables[0].Rows[0][0].ToString();
String PartNo = ExcelDataSet.Tables[0].Rows[0][1].ToString();
String DeliveryDt = Convert.ToDateTime(ExcelDataSet.Tables[0].Rows[0][3].ToString()).ToString("dd-MMM-yyyy");
String Location = ExcelDataSet.Tables[0].Rows[0][5].ToString();
String Qty = ExcelDataSet.Tables[0].Rows[0][7].ToString();
String PartyCode = ExcelDataSet.Tables[0].Rows[0][10].ToString();
dt.Rows.Add(DINumber, PartNo, DeliveryDt, Location, Qty, PartyCode);
ViewState["dt"] = dt;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
i++;
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}

view data using ID in asp.net

I want to view another page using
Response.redirect
but considering a customerID along with it. here is my button code:
protected void btnPlaceOrder_Click(object sender, EventArgs e)
{
string productids = string.Empty;
DataTable dt;
if (Session["MyCart"] != null)
{
dt = (DataTable)Session["MyCart"];
decimal totalPrice, totalProducts;
bool totalPriceConversionResult = decimal.TryParse(txtTotalPrice.Text, out totalPrice), totalProductsConversionResult = decimal.TryParse(txtTotalProducts.Text, out totalProducts);
ShoppingCart k = new ShoppingCart()
{
CustomerName = txtCustomerName.Text,
CustomerEmailID = txtCustomerEmailID.Text,
CustomerAddress = txtCustomerAddress.Text,
CustomerPhoneNo = txtCustomerPhoneNo.Text,
TotalProducts = totalProductsConversionResult ? Convert.ToInt32(totalProducts) : 0,
TotalPrice = totalPriceConversionResult ? Convert.ToInt32(totalPrice) : 0,
ProductList = productids,
PaymentMethod = rblPaymentMethod.SelectedItem.Text
};
DataTable dtResult = k.SaveCustomerDetails();
for (int i = 0; i < dt.Rows.Count; i++) // loop on how many products are added by the user
{
ShoppingCart SaveProducts = new ShoppingCart()
{
CustomerID = Convert.ToInt32(dtResult.Rows[0][0]),
ProductID = Convert.ToInt32(dt.Rows[i]["ProductID"]),
TotalProducts = Convert.ToInt32(dt.Rows[i]["ProductQuantity"]),
};
SaveProducts.SaveCustomerProducts();
}
Response.Redirect("Admin/OrderDetails.aspx?Id={0}");
What it does is that it gets all the user input then in the end, i want to show to the user his/her order summary. As you can see, i am trying to use Response.Redirect.
The problem is i want to use the current customerID when i use the
Response.Redirect("Admin/OrderDetails.aspx?Id={0}");
any tricks on this?
You have CustomerID already. Substitute {0} before redirecting with that value
var customerId = Convert.ToInt32(dtResult.Rows[0][0]);
Response.Redirect(String.Format("Admin/OrderDetails.aspx?Id={0}", customerId.ToString()));

linq to entity framework custom collection class that inherits list(Of T)

OK, I'm not quite sure how to ask this, but basically I want to create a custom collection class that allows me to have properties on a generic list (Of T) such as:
Public ReadOnly Property TotalCalories() As Decimal
Get
Dim decTotal As Decimal = 0D
For Each thisFoodDiaryItem As FoodDiaryItem In Me
Dim thisNutValue As NutritionalData = (From nd In thisFoodDiaryItem.Food.NutritionalDatas Where nd.NutritionalDefinitionID = 208).FirstOrDefault
If thisFoodDiaryItem.Food.FoodWeights.Count > 0 Then
Dim decWeight As Decimal = thisFoodDiaryItem.Food.FoodWeights(0).WeightInGrams
If Not thisNutValue Is Nothing Then
Dim decCalories As Decimal = Math.Round((thisNutValue.Value * (decWeight / 100)) * thisFoodDiaryItem.Amount)
decTotal += decCalories
End If
End If
Next
Return decTotal
End Get
End Property
Public ReadOnly Property TotalSugars() As Decimal
Get
Dim decTotal As Decimal = 0D
For Each thisFoodDiaryItem As FoodDiaryItem In Me
Dim thisNutValue As NutritionalData = (From nd In thisFoodDiaryItem.Food.NutritionalDatas Where nd.NutritionalDefinitionID = 269).FirstOrDefault
If thisFoodDiaryItem.Food.FoodWeights.Count > 0 Then
Dim decWeight As Decimal = thisFoodDiaryItem.Food.FoodWeights(0).WeightInGrams
If Not thisNutValue Is Nothing Then
Dim decCalories As Decimal = Math.Round((thisNutValue.Value * (decWeight / 100)) * thisFoodDiaryItem.Amount)
decTotal += decCalories
End If
End If
Next
Return decTotal
End Get
End Property
I want this class to be used when calling entity framework queries:
Protected Sub BindFoodDiaryItems()
CurrentFoodDiaryItems = New FoodDiaryItemCollection
CurrentFoodDiaryItems = (From fdi In db.FoodDiaryItems Where fdi.PersonID = CurrentSiteUser.PersonID And fdi.EntryDate = CurrentDiaryDate).ToList
If AllMeals Is Nothing Then
AllMeals = (From m In db.Meals).ToList
End If
lvMealsA.DataSource = AllMeals
lvMealsA.DataBind()
lblTotalCalories.Text = CurrentFoodDiaryItems.TotalCalories.ToString
lblTotalSugars.Text = CurrentFoodDiaryItems.TotalSugars.ToString
lblTotalFats.Text = CurrentFoodDiaryItems.TotalFat.ToString
lblTotalProtein.Text = CurrentFoodDiaryItems.TotalProtein.ToString
lblTotalCarbs.Text = CurrentFoodDiaryItems.TotalCarbs.ToString
End Sub
I'm assuming it would go something like this:
Partial Public Class FoodDiaryItemCollection
Inherits List(Of FoodDiaryItem)
Sub New()
End Sub
End Class
Error I'm getting:
Unable to cast object of type 'System.Collections.Generic.List`1[NutritionBridgeModel.FoodDiaryItem]' to type 'NutritionBridgeModel.FoodDiaryItemCollection'.
TIA
The .Net Framework exposes a lot of awesome extension methods, like Sum, Average, etc...
http://msdn.microsoft.com/en-us/library/bb341635
Example:
class Program
{
static void Main(string[] args)
{
var sweetList = new List<int> { 4, 123, 5, 23, 42 };
Console.WriteLine("Average: {0}", sweetList.Average());
Console.WriteLine("Sum: {0}", sweetList.Sum());
var listOfCoolObjects = new List<CoolObject>();
listOfCoolObjects.Add(new CoolObject { Name = "1434", NeatValue = 42 });
listOfCoolObjects.Add(new CoolObject { Name = "asdf", NeatValue = 5 });
listOfCoolObjects.Add(new CoolObject { Name = "fgsdfg", NeatValue = 99 });
listOfCoolObjects.Add(new CoolObject { Name = "qwerty", NeatValue = 1345 });
listOfCoolObjects.Add(new CoolObject { Name = "casc", NeatValue = 111 });
Console.WriteLine("Average: {0}", listOfCoolObjects.Average(x => x.NeatValue));
Console.WriteLine("Sum: {0}", listOfCoolObjects.Sum(x => x.NeatValue));
}
}
class CoolObject
{
public string Name { get; set; }
public int NeatValue { get; set; }
}
In your code, you could do something like this:
var sum = (From fdi In db.FoodDiaryItems Where fdi.PersonID = CurrentSiteUser.PersonID And fdi.EntryDate = CurrentDiaryDate).Sum(fdi => fdi.SomeValueYouWantToSum)
I know you're coding in VB, but I don't know VB at all, so excuse any syntax errors in that last code chunk.

When using the Grid-view(on devexpress -visual c#), how do I get the values of four fields of a record when I click on that record/row?

I want to get the values of four fields of a record and later use them in an sql statement. How can I get those 4 values when I click a row/record in gridview and have each value stored in their own declared variables?
The four field names are course_abbreviation, course_name, month_of_admission and year_of_admission.
public LecturerForm(string lecturer_firstname, string lecturer_lastname, string lecturer_id)
{
InitializeComponent();
string lecturer = lecturer_firstname + " " + lecturer_lastname;
lblname.Text = lecturer;
string lecID = lecturer_id;
string connetionString = null;
SqlConnection cnn;
connetionString = "Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=jms";
SqlDataAdapter sda = new SqlDataAdapter("Select unit_code, unit_name, course_abbreviation, course_name, group_name from units_allocation where national_id='" + lecID + "' ", connetionString);
cnn = new SqlConnection(connetionString);
DataTable dt4 = new System.Data.DataTable();
sda.Fill(dt4);
gridControl1.DataSource = dt4;
gridView1.Columns[0].Caption = "Unit Code";
gridView1.Columns[1].Caption = "Unit Name";
gridView1.Columns[2].Caption = "Course Abbr.";
gridView1.Columns[3].Caption = "Course Name";
gridView1.Columns[4].Caption = "Group";
}
private void gridView1_RowClick(object sender, RowClickEventArgs e)
{
//code to get values of four fields and store in four variables...(i.e from the question)
}
In the GridView.RowClick event there is the e.RowHandle argument which you can use to identify a clicked row. Then, use the GridView.GetRowCellValue method to get a cell value of that row.
object val1;
object val2;
object val3;
object val4;
private void gridView1_RowClick(object sender, RowClickEventArgs e) {
int rowHandle = e.RowHandle;
val1 = gridView1.GetRowCellValue(rowHandle, gridView1.Columns[0]);
val2 = gridView1.GetRowCellValue(rowHandle, gridView1.Columns[1]);
val3 = gridView1.GetRowCellValue(rowHandle, gridView1.Columns[2]);
val4 = gridView1.GetRowCellValue(rowHandle, gridView1.Columns[3]);
}
To avoid problems that occur when columns are dragged into different positions it is usually better to reference by name.
object val1;
object val2;
object val3;
object val4;
private void gridView1_RowClick(object sender, RowClickEventArgs e) {
int rowHandle = e.RowHandle;
val1 = gridView1.GetRowCellValue(rowHandle, "course_abbreviation");
val2 = gridView1.GetRowCellValue(rowHandle, "course_name");
val3 = gridView1.GetRowCellValue(rowHandle, "month_of_admission");
val4 = gridView1.GetRowCellValue(rowHandle, "year_of_admission");
}

Resources