Related
I have this ASP.NET project working with Oracle, I have the following code for operating the DB:
public int cmd_Execute_Orcl(string strSql, params OracleParameter[] paramArray)
{
OracleCommand myCmd = new OracleCommand();
try
{
myCmd.Connection = myOrclConn;
myCmd.CommandText = strSql;
foreach (OracleParameter temp in paramArray)
{
myCmd.Parameters.Add(temp);
}
ConnectionManage(true);
int i = myCmd.ExecuteNonQuery();
myCmd.Parameters.Clear();
return i;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myCmd.Dispose();
ConnectionManage(false);
}
}
"ConnectionManage()" turns on or off the connection, the following code is from data access layer of the program:
public string Edit_DAL(string id, string jh, string jz, string jd, string wd, string gzwz, string qxlx, string sx, string jx, string jb, string cfdd, string zjqssj, string zjzzsj, string bz)
{
string sql = "update JH set jh = :jh, jz = :jz, wd = :wd, jd = :jd, gzwz = :gzwz, qxlx = :qxlx, sx = :sx, jx = :jx, jb = :jb, cfdd = :cfdd, zjqssj = TO_DATE(:zjqssj, 'yyyy-mm-dd hh24:mi:ss'), zjzzsj = TO_DATE(:zjzzsj, 'yyyy-mm-dd hh24:mi:ss'), bz = :bz where ID = :idy";
string result = null;
{
String[] temp1 = zjqssj.Split('/');
String[] temp2 = zjzzsj.Split('/');
string tempString = "";
if (temp1[2].Length < 2)
{
temp1[2] = temp1[2].Insert(0, "0");
}
for (int i = 0; i < temp1.Length; i++)
{
if (i != 0)
{
temp1[i] = temp1[i].Insert(0, "/");
}
tempString += temp1[i].ToString();
}
zjqssj = tempString;
tempString = "";
if (temp2[2].Length < 2)
{
temp2[2] = temp2[2].Insert(0, "0");
}
for (int i = 0; i < temp2.Length; i++)
{
if (i != 0)
{
temp2[i] = temp2[i].Insert(0, "/");
}
tempString += temp2[i].ToString();
}
zjzzsj = tempString;
tempString = "";
}
OracleParameter[] pars ={
new OracleParameter(":idy",id),
new OracleParameter(":jh",jh),
new OracleParameter(":jz",jz),
new OracleParameter(":jd",jd),
new OracleParameter(":wd",wd),
new OracleParameter(":gzwz",gzwz),
new OracleParameter(":qxlx",qxlx),
new OracleParameter(":sx",sx),
new OracleParameter(":jx",jx),
new OracleParameter(":jb",jb),
new OracleParameter(":cfdd",cfdd),
new OracleParameter(":zjqssj",(zjqssj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":zjzzsj",(zjzzsj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":bz",bz)
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
result = "ok";
}
catch (Exception ex)
{
result = "no" + "=" + ex.Message + "\n" + ex.StackTrace;
}
return result;
}
Here's where the strange thing happens, when I hit this part of the code, there's no exception, it returns 0, no rows affected, all the values of the parameters are normal, with expected value, then I tried to run the command in PL/SQL and it works, the row is correctly updated, delete function is also referencing the same "cmd_Execute_Orcl" method and it works just fine, and for the other object the edit function is working perfectly, I am posting the code below:
public string Edit(string OriginalId, string EditUserAccount, string EditUserName, string EditUserMobile, string EditDeptId, string EditRoleId, string EditRoleName)
{
string sql = "update AuthUser set UserAccount=:EditUserAccount, UserName=:EditUserName, UserMobile=:EditUserMobile, DepartmentId=:EditDeptId, RID=:EditRoleId, RoleName=:EditRoleName where ID=:OriginalId";
OracleParameter[] pars ={
new OracleParameter(":EditUserAccount",EditUserAccount),
new OracleParameter(":EditUserName",EditUserName),
new OracleParameter(":EditUserMobile",EditUserMobile),
new OracleParameter(":EditDeptId",EditDeptId),
new OracleParameter(":EditRoleId",EditRoleId),
new OracleParameter(":EditRoleName",EditRoleName),
new OracleParameter(":OriginalId",OriginalId),
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
return "ok";
}
catch (Exception ex)
{
string test = ex.Message;
return "no";
}
}
In the expected table, column ID is nvarchar2 with default value of sys_guid(), column ZJQSSJ and column ZJZZSJ is of type date, all other columns are of type varchar2, I have also tried executing "COMMIT" and reformating data for date, but the same problem is still there, plz help...
I've created this two extensions in Kotlin to Encrypt/Decrypt strings:
fun String.encrypt(seed : String): String {
val keyGenerator = KeyGenerator.getInstance("AES")
val secureRandom = SecureRandom.getInstance("SHA1PRNG")
secureRandom.setSeed(seed.toByteArray())
keyGenerator.init(128, secureRandom)
val skey = keyGenerator.generateKey()
val rawKey : ByteArray = skey.encoded
val skeySpec = SecretKeySpec(rawKey, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
val byteArray = cipher.doFinal(this.toByteArray())
return byteArray.toString()
}
fun String.decrypt(seed : String): String {
val keyGenerator = KeyGenerator.getInstance("AES")
val secureRandom = SecureRandom.getInstance("SHA1PRNG")
secureRandom.setSeed(seed.toByteArray())
keyGenerator.init(128, secureRandom)
val skey = keyGenerator.generateKey()
val rawKey : ByteArray = skey.encoded
val skeySpec = SecretKeySpec(rawKey, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, skeySpec)
val byteArray = cipher.doFinal(this.toByteArray())
return byteArray.toString()
}
for some reason I'm getting the following exception:
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
What I'm doing wrong?
AES Encryption / Decryption using base64 key, salt and iv (Initialization Vector).
object AESEncyption {
const val secretKey = "tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ="
const val salt = "QWlGNHNhMTJTQWZ2bGhpV3U=" // base64 decode => AiF4sa12SAfvlhiWu
const val iv = "bVQzNFNhRkQ1Njc4UUFaWA==" // base64 decode => mT34SaFD5678QAZX
fun encrypt(strToEncrypt: String) : String?
{
try
{
val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
val tmp = factory.generateSecret(spec)
val secretKey = SecretKeySpec(tmp.encoded, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)
return Base64.encodeToString(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)), Base64.DEFAULT)
}
catch (e: Exception)
{
println("Error while encrypting: $e")
}
return null
}
fun decrypt(strToDecrypt : String) : String? {
try
{
val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
val tmp = factory.generateSecret(spec);
val secretKey = SecretKeySpec(tmp.encoded, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
return String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT)))
}
catch (e : Exception) {
println("Error while decrypting: $e");
}
return null
}
}
iOS swift
Following Maarten Bodews guides I fix the issues as:
fun String.encrypt(password: String): String {
val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES")
val iv = ByteArray(16)
val charArray = password.toCharArray()
for (i in 0 until charArray.size){
iv[i] = charArray[i].toByte()
}
val ivParameterSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
val encryptedValue = cipher.doFinal(this.toByteArray())
return Base64.encodeToString(encryptedValue, Base64.DEFAULT)
}
fun String.decrypt(password: String): String {
val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES")
val iv = ByteArray(16)
val charArray = password.toCharArray()
for (i in 0 until charArray.size){
iv[i] = charArray[i].toByte()
}
val ivParameterSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
val decryptedByteValue = cipher.doFinal(Base64.decode(this, Base64.DEFAULT))
return String(decryptedByteValue)
}
To encode your ciphertext use base 64 or hexadecimals. The Java API contains a Base64 class, so you're probably best off using that.
byte[]#toString doesn't do what you expect it to do; it simply returns a representation of the byte array reference, not the contents of the byte array.
Besides that:
don't use SecureRandom to derive a key, try and lookup PBKDF2;
explicitly use a mode of operation such as "AES/GCM/NoPadding";
use a unique IV, and a random IV if you decide to use CBC (usually insecure);
don't use toByteArray without explicitly selecting a character encoding for the message.
The easiest way of implementing AES Encryption and Decryption in Android is to copy this class in your projects.
Encrypt Strings
Please copy the AESUtils class in your project first and then you can use it like this.
String encrypted = "";
String sourceStr = "This is any source string";
try {
encrypted = AESUtils.encrypt(sourceStr);
Log.d("TEST", "encrypted:" + encrypted);
} catch (Exception e) {
e.printStackTrace();
}
Decrypt Strings
String encrypted = "ANY_ENCRYPTED_STRING_HERE";
String decrypted = "";
try {
decrypted = AESUtils.decrypt(encrypted);
Log.d("TEST", "decrypted:" + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
AESUtils Class
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils
{
private static final byte[] keyValue =
new byte[]{'c', 'o', 'd', 'i', 'n', 'g', 'a', 'f', 'f', 'a', 'i', 'r', 's', 'c', 'o', 'm'};
public static String encrypt(String cleartext)
throws Exception {
byte[] rawKey = getRawKey();
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String encrypted)
throws Exception {
byte[] enc = toByte(encrypted);
byte[] result = decrypt(enc);
return new String(result);
}
private static byte[] getRawKey() throws Exception {
SecretKey key = new SecretKeySpec(keyValue, "AES");
byte[] raw = key.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKey skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] encrypted)
throws Exception {
SecretKey skeySpec = new SecretKeySpec(keyValue, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
You can Encrypt and Decrypt in Kotlin like this
first you need:
val SECRET_KEY = "secretKey"
val SECRET_IV = "secretIV"
after that
Encrypt:
private fun String.encryptCBC(): String {
val iv = IvParameterSpec(SECRET_IV.toByteArray())
val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv)
val crypted = cipher.doFinal(this.toByteArray())
val encodedByte = Base64.encode(crypted, Base64.DEFAULT)
return String(encodedByte)
}
and Decrypt:
private fun String.decryptCBC(): String {
val decodedByte: ByteArray = Base64.decode(this, Base64.DEFAULT)
val iv = IvParameterSpec(SECRET_IV.toByteArray())
val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv)
val output = cipher.doFinal(decodedByte)
return String(output)
}
after that you can use it like this:
val strEncrypt = edt.text.toString().encryptCBC()
val strDecrypted = strEncrypt?.decryptCBC()
Following MarcForn guide I reduce it like this this:
const val encryptionKey = "ENCRYPTION_KEY"
fun String.cipherEncrypt(encryptionKey: String): String? {
try {
val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES")
val iv = encryptionKey.toByteArray()
val ivParameterSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
val encryptedValue = cipher.doFinal(this.toByteArray())
return Base64.encodeToString(encryptedValue, Base64.DEFAULT)
} catch (e: Exception) {
e.message?.let{ Log.e("encryptor", it) }
}
return null
}
fun String.cipherDecrypt(encryptionKey: String): String? {
try {
val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES")
val iv = encryptionKey.toByteArray()
val ivParameterSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
val decodedValue = Base64.decode(this, Base64.DEFAULT)
val decryptedValue = cipher.doFinal(decodedValue)
return String(decryptedValue)
} catch (e: Exception) {
e.message?.let{ Log.e("decryptor", it) }
}
return null
}
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
}
string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}
I checked my code over and over. But i cant seem to find where this error occurs.
Here is my code:
public static string MerchantUpdate(string firstN, string lastN, int type, int reseller, string CoName, string site, int industry, bool isact, bool isdel, string houseNO, string street, string town, string city, string state, string zipcode, int countryID, string telephone, string fax, string userN, string emailA, string secQ, string secA, decimal set, decimal month, decimal dep, decimal with, decimal eTrans, decimal acct, DateTime created)
{
string retmerUpdate = "";
string merUpdate = "UPDATE MerchantMaster SET FirstName = #fname, LastName = #lname, MerchantTypeID = #typeID, ResellerMasterID = #resellerID, "
+ "CompanyName = #CoName, Url = #url, IndustryID = #IndustryID, IsActive = #isact, IsDeleted = #isdel, HouseNo = hnumber, "
+ "StreetAddress = #address, Town = #townAD, City = #cityAD, State = #stateAD, ZipCode = #zipC, CountryID = #countryID, "
+ "TelephoneNo = #teleNo, FaxNo = #faxNo, UserName = #uName, EmailAdr = #eAD, SecurityQ = #secQ, SecurityA = #secA, Setup = #set, "
+ "Monthly = #month, Deposit = #dep, Withdraw = #with, EmailTransfer = #eTrans, AccTransfer = #acct, DateCreated = #created WHERE id = #id";
string[] param = { "#fname", "#lname", "#typeID", "#resellerID", "#CoName", "#url", "#IndustryID", "#isact", "#isdel", "#hnumber", "#address", "#townAD", "#cityAD", "#stateAD", "#zipC", "#countryID", "#teleNo", "#faxNo", "#uName", "#eAD", "#secQ", "#secA", "#set", "#month", "#dep", "#with", "#eTrans", "#acct", "#created" };
object[] paramVal = { firstN, lastN, type, reseller, CoName, site, industry, isact, isdel, houseNO, street, town, city, state, zipcode, countryID, telephone, fax, userN, emailA, secQ, secA, set, month, dep, with, eTrans, acct, created};
try
{
ClassDBQuery.ExecNonQuery(merUpdate, param, paramVal);
retmerUpdate = "success";
}
catch (Exception ex)
{
retmerUpdate = ex.Message;
}
return retmerUpdate;
}
Here is my code behind:
using (SqlConnection connectString = new SqlConnection(GetConnectString()))
//update merchant master
try
{
int idses = Convert.ToInt32(Session["ID"].ToString());
string merUpdate = ClassMerchant.MerchantUpdate(fName.Text, lName.Text, Convert.ToInt32(ddlT.SelectedValue), Convert.ToInt32(ddlR.SelectedValue), CompName.Text, website.Text, Convert.ToInt32(ddlI.SelectedValue), true, false, houseN.Text, streetAD.Text, townAD.Text, cityAD.Text, stateAD.Text, zipC.Text, Convert.ToInt32(ddlC.SelectedValue), teleNumb.Text, faxNumb.Text, userN.Text, Eaddress.Text, secQuest.Text, secAns.Text, Convert.ToDecimal(set.Text), Convert.ToDecimal(month.Text), Convert.ToDecimal(dep.Text), Convert.ToDecimal(with.Text), Convert.ToDecimal(etrans.Text), Convert.ToDecimal(aTrans.Text), DateTime.Now);
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
finally
{
if (connectString.State == System.Data.ConnectionState.Open)
connectString.Close();
}
Please help me.
hnumber is missing # in front of it