Synchronization local database and the remote database using php and c#? - c#

I want to sync and up-to-date the local database and the remote database concurrently. The owner have four restaurants(A, B, C, D) at different places. He maintains same price for products and same quality in all four restaurants. So he uses remote database to change price which used to affect the changed price in all branches. All four branches and remote server have the same database structure and same tables(i.e : A branch has records also other branch. Every branch every tables are uniquely identified by id and branch field(id + branch as composite key).
Sample table (purchase)
+----+--------+------------+------------+-----+--------------------+---------------------+
| id | branch | item | unit_price | qty | added_on | last_updated |
+----+--------+------------+------------+-----+--------------------+---------------------+
| 1 | A | Pizza | 800 | 5 |2018-12-05T15:47:54 | 2018-05-11T15:47:54 |
+----+--------+------------+------------+-----+--------------------+---------------------+
| 2 | A | Chicken | 350 | 5 |2018-12-05T15:49:54 | 2018-05-11T15:50:54 |
+----+--------+------------+------------+-----+--------------------+---------------------+
| 2 | B | cappuccino | 280 | 7 |2018-12-05T15:47:24 | 2018-05-11T15:47:24 |
+----+--------+------------+------------+-----+--------------------+---------------------+
I have the following code to extract newly added record and updated record (with the field added_on and last_updated) from local database then upload and import in remote database with a timer. Here the checked time to extract records from local database is stored in a file which will use by the timer.
Now, to-up-to-date the local database(download other branch records) in every branch how can I download the newly inserted records and updated records from the remote server?
php script on remote server ( To insert on remote database)(execute.php)
<?php
try
{
$connect = mysqli_connect("localhost", "username", "password", "database");
$query = '';
$table_data = '';
$filename = "app_restaurant.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach ($array as $set)
{
$tblName = $set['tableName'];
if (sizeof($set['rows']) > 0)
{
$query = '';
$colList = array();
$valList = array();
// Get list of column names
foreach ($set['rows'][0] as $colName => $dataval)
{
$colList[] = "`" . $colName . "`";
}
$query .= "INSERT INTO `" . $tblName . "` \n";
$query .= "(" . implode(",", $colList) . ")\nVALUES\n";
// Go through the rows for this table.
foreach ($set['rows'] as $idx => $row)
{
$colDataA = array();
// Get the data values for this row.
foreach ($row as $colName => $colData)
{
$colDataA[] = "'" . $colData . "'";
}
$valList[] = "(" . implode(",", $colDataA) . ")";
}
// Add values to the query.
$query .= implode(",\n", $valList) . "\n";
// If id column present, add ON DUPLICATE KEY UPDATE clause
if (in_array("`id`", $colList))
{
$query .= "ON DUPLICATE KEY UPDATE\n\t";
$tmp = array();
foreach ($colList as $idx => $colName)
{
//$tmp[] = $colName." = new.".$colName." ";
// Changed the following line to get value from current insert row data
$tmp[] = $colName . " = VALUES(" . $colName . ") ";
}
$query .= implode(",", $tmp) . "\n";
}
else
{
echo "<p><b>`id`</b> column not found. <i>ON DUPLICATE KEY UPDATE</i> clause <b>NOT</b> added.</p>\n";
echo "<p>Columns Found:<pre>" . print_r($colList, true) . "</pre></p>\n";
}
echo "<p>Insert query:<pre>$query</pre></p>";
$r = mysqli_query($connect, $query);
echo mysqli_errno($connect) . ": " . mysqli_error($connect) . "\n";
echo "<h1>" . mysqli_affected_rows($connect) . " Rows appended in .$tblName.</h1>";
}
else
{
echo "<p>No rows to insert for .$tblName.</p>";
}
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>
file up-loader(upload.php)
<?php
$filepath = $_FILES["file"]["tmp_name"];
move_uploaded_file($filepath,"app_restaurant.json");
?>
1.create JSON file from local database
private void btnExportJson_Click(object sender, EventArgs e)
{
string filePath = #"C:\Users\testeam-PC\Desktop\app_restaurant.json";
if(File.Exists(filePath))
{
MessageBox.Show("Sorry! The file is already exists, Please restart the operation","File Exists");
File.Delete(filePath);
}
else
{
MySQL mysql = new MySQL();
var source_result = false;
source_result = mysql.check_connection(myConString);
if (source_result == false)
{
MessageBox.Show("Sorry! Unable to connect with XAMP / WAMP or MySQL.\n Please make sure that MySQL is running.", "Local Database Connection Failure");
}
else
{
// MessageBox.Show("Connected");
int count = 0;
using (var connection = new MySqlConnection(myConString))
{
connection.Open();
// get the names of all tables in the chosen database
var tableNames = new List<string>();
using (var command = new MySqlCommand(#"SELECT table_name FROM information_schema.tables where table_schema = #database", connection))
{
command.Parameters.AddWithValue("#database", "app_restaurant");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
tableNames.Add(reader.GetString(0));
}
}
// open a JSON file for output; use the streaming JsonTextWriter interface to avoid high memory usage
using (var streamWriter = new StreamWriter(filePath))
// For seperate lines may be huge capacity
using (var jsonWriter = new JsonTextWriter(streamWriter) { Formatting = Newtonsoft.Json.Formatting.Indented, Indentation = 2, IndentChar = ' ' })
//using (var jsonWriter = new JsonTextWriter(streamWriter) )
{
// one array to hold all tables
jsonWriter.WriteStartArray();
foreach (var tableName in tableNames)
{
//MessageBox.Show(tableName);
count += 1;
// an object for each table
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("tableName");
jsonWriter.WriteValue(tableName);
jsonWriter.WritePropertyName("rows");
// an array for all the rows in the table
jsonWriter.WriteStartArray();
// select all the data from each table
using (var command = new MySqlCommand(#"SELECT * FROM " + tableName + " WHERE (last_updated >= '" + local_checked_time + "') OR (added_on >= '" + local_checked_time + "')", connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// write each row as a JSON object
jsonWriter.WriteStartObject();
for (int i = 0; i < reader.FieldCount; i++)
{
jsonWriter.WritePropertyName(reader.GetName(i));
jsonWriter.WriteValue(reader.GetValue(i));
}
jsonWriter.WriteEndObject();
}
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
MessageBox.Show("Totally " + count + " tables circulated", "Success");
btnUploadToServer.Enabled = true;
// Application.Exit();
//btnUploadToServer_Click(sender, e);
}
}
}
}
}
2.upload the JSON file to server
private void btnUploadToServer_Click(object sender, EventArgs e)
{
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
//MessageBox.Show("Internet Available");
try
{
using (WebClient client = new WebClient())
{
string filePath = #"C:\Users\testeam-PC\Desktop\app_restaurant.json";
var myUri = new Uri(#"http://youraddress.com/path/upload.php");
client.UploadFile(myUri, filePath);
client.Credentials = CredentialCache.DefaultCredentials;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
MessageBox.Show("Successfully Uploaded", "Success");
btnExecuteURL.Enabled = true;
// btnExecuteURL_Click(sender, e);
}
else
{
MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
}
}
3.Execute the file
private void btnExecuteURL_Click(object sender, EventArgs e) {
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true) {
//MessageBox.Show("Internet Available");
try {
// Launch the execution code...
System.Diagnostics.Process.Start("http://youraddress.com/path/execute.php");
}
catch(Exception err) {
MessageBox.Show(err.Message);
}
}
else {
MessageBox.Show("There is no internet connection.\n Please make sure that you have internet connection.", "No Internet");
}
}

Related

Insert Data using Json in C#

I have some problem in inserting data to my free webhost mysql using JSON in C#. This is what I have done :
Php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP REQUEST Request
*/
require_once __DIR__ . '/db_connect.php';
//require_once __DIR__ . '/generateIDrandom.php';
require_once __DIR__ . '/Configuration.php';
$db = new DB_CONNECT();
$connstring = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// array for JSON response
$response = array();
// check for required fields
if (isset($_REQUEST['WSID'])) {
$wsid = $_REQUEST['WSID'];
$jenismesin = $_REQUEST['JenisMesin'];
$merk = $_REQUEST['MerkMesin'];
$lokasi = $_REQUEST['Lokasi'];
$inlok = $_REQUEST['InisialLokasi'];
$limit = $_REQUEST['LimitMesin'];
$denom = $_REQUEST['Denom'];
$tim4 = $_REQUEST['Tim4'];
$tim5 = $_REQUEST['Tim5'];
$status = "1";
// connecting to db
$result = mysqli_query($connstring, "insert into MasterATM (WSID, JenisMesin, MerkMesin, Lokasi, InisialLokasi, LimitMesin, Denom, Tim4, Tim5, Status) values ('$wsid','$jenismesin','$merk','$lokasi', '$inlok', '$limit', '$denom','$tim4','$tim5','$status')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Upload Successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
C#
private void InputBtn_Click(object sender, EventArgs e)
{
try
{
WebRequest request = WebRequest.Create("https://xxx.000webhostapp.com/php/InsertDataMesin.php?WSID =" + WSIDBox.Text + "& JenisMesin = " + TipeMesinBox.SelectedItem + "& MerkMesin = " + MerkMesinCB.SelectedItem + "& Lokasi= " + LokasiBox.Text + "& InisialLokasi = " + InisialLokasiBox.Text + "& LimitMesin= " + LimitBox.Text + "& Denom= " + DenomBox.Text + "& Tim4= '" + Tim4CB.SelectedItem + "& Tim5= '" + Tim5CB.SelectedItem + "& Status = 1");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string json = stream.ReadToEnd();
stream.Close();
var result = JsonConvert.DeserializeObject(json);
MessageBox.Show("Data berhasil ditambahkan !");
TampilDataEdit();
}
catch
{
MessageBox.Show("Data gagal ditambahkan. Silakan coba lagi");
}
}
When I run my program, there is no some error. But when I see to my database, there is no data inserted. So, How can I insert data using json c# ?

Why do my database commands only work when I interrupt them with MessageBox.Show() calls?

With the following code, only the first set of database commands are actually carried out to fruition (one table is dropped, others have a record deleted from them) IF the MessageBox.Show() call at the beginning of DropTablesAndDeleteFromTables() is commented out.
If I uncomment it, so that the user has to dismiss after each set of database manipulations (obviously not what I want in the version to be used by customers), all is well - all the tables are dropped, and references to them deleted, as desired. Why does interrupting the process in this way (computus interruptus?) make the difference between success and failure, and how can I have my pie and eat it, too (get all the database commands to succeed without bothering the user with N MessageBox.Show() dialogs to dismiss?
private void DropTablesAndDeleteFromTables(string recordType, string fileName)
{
MessageBox.Show(String.Format("In DropTablesAndDeleteFromTables(), recordType is {0}, fileName is {1}", recordType, fileName)); //TODO: Remove
try
{
WorkFiles wrkFile = new WorkFiles();
int tableOK = 0;
DataSet workfiles;
tableOK = wrkFile.isValidWorkTable();
if (tableOK > 0) //Table has at least one record
{
workfiles = wrkFile.getAllRecords();
//Go thru dataset and find filename to clean up after
foreach (DataRow row in workfiles.Tables[0].Rows)
{
string tmpType = row["fileType"].ToString();
if (tmpType.EndsWith("0") || tmpType.EndsWith("1"))
{
tmpType = tmpType.Substring(0, 3);
}
string tmpStr = row["Name"].ToString();
int intSite = (int) row["siteNo"];
string tmpName = tmpType + "_" + intSite.ToString() + "_" + tmpStr;
if (tmpType != recordType) continue;
if (tmpName != fileName) continue;
//Drop workTables table from site-specific DB [ such as from HHSDB003.SDF ]
String dropTable = "DROP TABLE " + tmpType + tmpStr;
String delWorkTableSimple = string.Format("DELETE FROM workTables WHERE filetype = '{0}' and Name = '{1}'", tmpType, tmpStr);
String delWorkTable0 = "DELETE FROM workTables WHERE filetype = '" + tmpType + "0' and Name = '" + tmpStr + "'";
String delWorkTable1 = "DELETE FROM workTables WHERE filetype = '" + tmpType + "1' and Name = '" + tmpStr + "'";
// Do site-specific database first
// 0) Drop the table whose contents have been sent
SendCommandToDB(dropTable, intSite, true);
PauseThatRefreshes();
// 1) Delete record from site-specific [ HHSDB[siteNum].SDF workTables, such as HHSDB003.SDF ]
SendCommandToDB(delWorkTableSimple, intSite, true);
PauseThatRefreshes();
// Bypassing the "0" and "1" tables did nothing - still only drops one table and deletes
// 2) Same as 1, but for table named [DSD,INV}0_Bla
SendCommandToDB(delWorkTable0, intSite, true);
PauseThatRefreshes();
// 3) Same as 2, but for table named [DSD,INV}1_Bla instead of [DSD,INV}0_Bla
SendCommandToDB(delWorkTable1, intSite, true);
PauseThatRefreshes();
// Four calls to site-specific above; Three-four calls to NON-site-specific below
// 4) Delete record from NON-site-specific [ HHSDB[siteNum].SDF workTables, such as HHSDB003.SDF ]
SendCommandToDB(delWorkTableSimple, intSite, false);
PauseThatRefreshes();
// 5) Same as 1, but for table named [DSD,INV}0_Bla
SendCommandToDB(delWorkTable0, intSite, false);
PauseThatRefreshes();
// 6) Same as 2, but for table named [DSD,INV}1_Bla instead of [DSD,INV}0_Bla
SendCommandToDB(delWorkTable1, intSite, false);
PauseThatRefreshes();
// 7) Conditionally delete a record (if a DSD record, from DSDHeader, which is in the base (NON-site-specific) database
if (tmpType == "DSD")
{
String dml = string.Format("DELETE FROM {0}Header WHERE Name = '{1}'", tmpType, tmpStr);
SendCommandToDB(dml, intSite, false);
}
populateTransactionListBoxWithWorkTables();
return;
} // foreach (DataRow row in workfiles.Tables[0].Rows)
} // if ( tableOK > 0) //Table exist
//} // lock TFS#4054
} // try
catch (Exception ex)
{
SSCS.ExceptionHandler(ex, "frmCentral.DropTablesAndDeleteFromTables");
}
} // DropTablesAndDeleteFromTables
private void PauseThatRefreshes()
{
int j = 0;
while (j < 100000)
{
j++;
}
}
private void SendCommandToDB(String sql, int siteNum, bool SiteSpecificDB)
{
try
{
if (SiteSpecificDB)
{
if (dbconn.InBaseDatabase())
{
dbconn = DBConnection.GetInstance(siteNum.ToString());
}
}
else
{
if (!(dbconn.InBaseDatabase()))
{
dbconn = DBConnection.GetInstance();
}
}
dbconn.DBCommand(sql, true);
}
catch (SqlCeException ee)
{
. . .
}
}
What is a workaround to let the process come up for air without forcing the user to play a role in the charade?
UPDATE
It seems to be a matter of how much time elapses between each set of database manipulations. When I changed this:
while (i < 100000)
... in PauseThatRefreshes() to this:
while (i < 10000000)
(with the MessageBox.Show() commented out) it worked! But that still makes me nervous. Is there a more "scientific" (elegant?) way to accomplish this?
Your code example is both too complicated, and incomplete. So I can't say for sure what's wrong.
But the symptom is a classic indication that you are a) running the code in question on the main GUI thread, and b) that code at some point winds up blocked waiting for the main GUI thread to do something else (i.e. deadlock).
The right way to fix it is to perform those operations on a different thread than the main GUI thread. This will most likely introduce new problems where you are accessing GUI elements from the operation, which you'll have to address by using your GUI API's "Invoke" mechanism.

Calling php script using C# (Unity)

I'm fairly new to both Unity and PHP, and I am currently working on a project where I can parse data from a MySQL database to Unity, using PHP.
I initially wanted to try and enable a method where the user can perhaps change the php script and enable it to choose a different table of data, however I was advised that it may be safer to list all variables within the php script and call it from Unity accordingly;
Display.php
$table = mysql_real_escape_string($_GET['table'], $db);
if ($table == "shoes") {
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
elseif ($table == "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
I'm having trouble calling the php and choosing the table that I want to select, I am pretty new to this, so I apologise if this seems completely incompetent to you guys.
Here is the my Unity Script;
HSController.cs
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
IEnumerator GetScores()
{
gameObject.guiText.text = "Loading...";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
gameObject.guiText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
Any help or a point in the right direction would be great!
Kind Regards
Let me try to rewrite this into a working example:
C#
void Start() {
StartCoroutine(GetData());
}
IEnumerator GetData() {
gameObject.guiText.text = "Loading...";
WWW www = new WWW("http://yoururl.com/yourphp.php?table=shoes"); //GET data is sent via the URL
while(!www.isDone && string.IsNullOrEmpty(www.error)) {
gameObject.guiText.text = "Loading... " + www.Progress.ToString("0%"); //Show progress
yield return null;
}
if(string.IsNullOrEmpty(www.error)) gameObject.guiText.text = www.text;
else Debug.LogWarning(www.error);
}
PHP
<?php
//DB connection goes here
if ($_REQUEST['table'] === "shoes") { //I'm using REQUEST instead of GET, so it will work with both GET and POST
$query = "SELECT * FROM `shoes` ORDER by `price` ASC LIMIT 10";
} elseif ($_REQUEST['table'] === "sneakers") {
$query = "SELECT * FROM `sneakers` ORDER by `price` ASC LIMIT 10";
}
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['shopname'] . "\t" . $row['price'] . "\n";
}
?>
Hope this helps!

How to display errors on a page without validation Summary?

I am working on a project in which i read multiple field from an excel file and save them in db.How to show multiple errors messages on a page if user enters wrong value. Aspose.cells is used for reading data.My code is
public List<Data> ImportFromExcel(Stream bytes, out bool isFine)
{
isFine = true;
DateTime DOJ;
List<Data> list = new List<Data>();
DataTable dt = new DataTable();
Workbook workBook = new Workbook();
workBook.Open(bytes);
Worksheet workSheet = workBook.Worksheets[0];
try
{
dt = workSheet.Cells.ExportDataTable(0, 0, workSheet.Cells.MaxRow + 1, workSheet.Cells.MaxColumn + 1, true);
}
catch (Exception ex)
{
isFine = false;
ShowMessage("Your file has some invalid formats of data. Please review it and try again.", MessageType.Error, true);
return null;
}
try
{
int i = 1;
foreach (DataRow reader in dt.Rows)
{
if (reader["LetterId"].ToString().Length > 75)
{
isFine = false;
ShowMessage("In Row Number " + i + " Letter Id cannot exceed 75 characters.", MessageType.Error, true);
return null;
}
if (reader["Subject"].ToString().Length > 75)
{
isFine = false;
ShowMessage("In Row Number " + i + " Subject cannot exceed 75 characters.", MessageType.Error, true);
return null;
}
.
.
.
Show message method shows only single error message.
You could create an empty list of strings, and then each time you encounter an error just add it to the list. Then once you have all the errors in your list, you can just do this:
string allErrors = string.Empty;
foreach (string err in errorList)
{
allErrors += err + "<br />";
}
if (allErrors != string.Empty)
{
ShowMessage(allErrors);
}

Issue of Sending Bulk Data as XML tag to SQL server

I am inserting bulk data(serial number,pin number) to DB.Before inserting,the data from datatable is binded into XML tag.Here the pin number is encrypted one...as follows,
strXml = "<?xml<pre lang="c#"></pre> version=" + #"""1.0"" encoding=" + #"""iso-8859-1""?><batch>";
strPinXml =strPinXml + "<data cardid="+#"""" +strid+#""""+" pinnumber=" + #"""" + myRC4Engine.CryptedText + #"""" + "></data>";
strXml = strXml + strPinXml + "</batch>";
Problem is after inserting into db, to verify whether the actual pinnumber(encrypted format in db) is inserted, i decrypted the pinnumber and found that,
The first digit in all data are displaced by (’)single quote and last
digit for some pinnumber is empty (if the pinnumber is-œA_¡/Ì·ÞvËÛ
(ie)ending in Û for that pins last digit is empty).
Please note that i'am using SQL server 2000 in this application
Please provide the solution to resolve this issue
Result as follows
Pins before inserting into db
Pinnumber(While inserting)
(Encrypted format) --- (Decrypted format)
šA [¦,ȵØzËÚ --------- 7613051524692
œA ¡/Ì•ÞvËÛ --------- 1687765748683
™# X¦!Ï´ÝÎÛ --------- 4770086471383
žA Z¡+ɹÝwÏÒ --------- 3642720979218
•O Q¢(˹Þ{ËÛ --------- 8879412945686
ŸO^¡,ȶÝ}Î× --------- 2846751673342
Pins retrieved from db after insertion
Pinnumber (Retrieved from db) ---- Retrieved pinnumber
(Encrypted format) --------------- (Decrypted format)
A [¦,ȵØzËÚ ------------------- ’613051524692
A _¡/Ì•ÞvËÛ ------------------- ’68776574868
# X¦!Ï´ÝÎÛ ------------------ ’77008647138
A Z¡+ɹÝwÏÒ ----------------- ’642720979218
O Q¢(˹Þ{ËÛ ------------------- ’879412945686
O ^¡,ȶÝ}Î× ------------------ ’846751673342
Application coding as follows
try
{
RC4Engine myRC4Engine = new RC4Engine();
myRC4Engine.EncryptionKey = "ab48495fdjk4950dj39405fk";
strXml = "<?xml version=" + #"""1.0"" encoding=" + #"""iso-8859-1""?> <batch>";
foreach (DataRow lobjbaseBatchDetail in dt.Rows)
{
myRC4Engine.InClearText = lobjbaseBatchDetail[3].ToString();
myRC4Engine.Encrypt();
strCardid = lobjbaseBatchDetail[0].ToString();
strBatchid = lobjbaseBatchDetail[1].ToString();
strid = strCardid + strBatchid + lobjbaseBatchDetail[2].ToString();
strPinXml =strPinXml + "<data cardid="+#"""" +strid+#""""+
" pinnumber=" + #"""" + myRC4Engine.CryptedText + #"""" + "></data>";
}
strXml = strXml + strPinXml + "</batch>";
SqlParameter[] arrParam = new SqlParameter[1];
arrParam[0] = new SqlParameter("#BATCHUPLOAD_XML", SqlDbType.Text );
arrParam[0].Direction = ParameterDirection.Input;
arrParam[0].Value = strXml;
iResult = SqlHelper.ExecuteNonQuery(objTrans, CommandType.StoredProcedure, "test_proc", arrParam);
objTrans.Commit();
}
catch(Exception ex)
{
objTrans.Rollback();
throw new Exception("Upload failed :" + ex.Message);
}
procedure
create procedure test_proc
(
#BATCHUPLOAD_XML text
)
as
begin
DECLARE #idoc INT
EXEC sp_xml_preparedocument #idoc OUTPUT, #BATCHUPLOAD_XML
insert into test_table_new
SELECT cardid,pinnumber
FROM OPENXML (#idoc, '/batch/data')
WITH (cardid varchar(100) '#cardid', pinnumber nvarchar(200) '#pinnumber')
EXEC sp_xml_removedocument #idoc
end
You shouldn't write the xml by hand. Let C#'s LinqToXml do it for you and it won't make mistakes.
You could write it like:
try
{
RC4Engine myRC4Engine = new RC4Engine();
myRC4Engine.EncryptionKey = "ab48495fdjk4950dj39405fk";
XDocument doc = new XDocument(
new XDeclaration("1.0", "iso-8859-1", null),
new XElement("batch"));
foreach (DataRow lobjbaseBatchDetail in dt.Rows)
{
myRC4Engine.InClearText = lobjbaseBatchDetail[3].ToString();
myRC4Engine.Encrypt();
strCardid = lobjbaseBatchDetail[0].ToString();
strBatchid = lobjbaseBatchDetail[1].ToString();
strid = strCardid + strBatchid + lobjbaseBatchDetail[2].ToString();
XElement data = new XElement("data");
data.Add(new XAttribute("cardid", strid));
data.Add(new XAttribute("pinnumber", myRC4Engine.CryptedText));
doc.Root.Add(data);
}
SqlParameter[] arrParam = new SqlParameter[1];
arrParam[0] = new SqlParameter("#BATCHUPLOAD_XML", SqlDbType.Text );
arrParam[0].Direction = ParameterDirection.Input;
arrParam[0].Value = doc.Declaration.ToString() +
doc.ToString(SaveOptions.DisableFormatting);
iResult = SqlHelper.ExecuteNonQuery(objTrans, CommandType.StoredProcedure, "test_proc", arrParam);
objTrans.Commit();
}
catch(Exception ex)
{
objTrans.Rollback();
throw new Exception("Upload failed :" + ex.Message);
}
RC4-encrypted information is binary data, not text. CryptedText shouldn't be typed as string. To wrap binary data in XML, you probably want to use the binary data's BASE64 encoding.

Categories