C# File list in reverse order. (Without Using Linq) - c#

I have searched around and it seem's the only answer I can get is to do with LINQ, which I don't have available on my visual stuido 2005.
I am building a program that reads files and imports them into a database, the way it's set up at the moment, it reads the very latest date it finds.
I want to read the earliest file first.
Is there any way around this?
Here is my code
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};;persist security info=false;Extended Properties=dBase IV", mDirectory);
this.richTextBox1.Text = connectionString;
try
{
foreach (string file in mFiles)
{
mDirectory = #"C:\USERS\DESKTOP\Test Pressure\";
mFiles = System.IO.Directory.GetFiles(mDirectory, "*(WIDE).DBF");
DateTime dt = File.GetLastWriteTime(file);
string newdate = dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime DBTIME = new DateTime(2014, 01, 01, 00, 00, 00);
string date = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DBTIME);
//this.richTextBox1.Text = date;
if (dt > DBTIME)
{
StringBuilder sb = new StringBuilder(300);
int n = GetShortPathName(file, sb, 300);
if (n == 0) // check for errors
MessageBox.Show(Marshal.GetLastWin32Error().ToString());
else
{ }
string filenameWithoutPath1 = System.IO.Path.GetFileName(sb.ToString());
string queryString = string.Format("SELECT * FROM [" + "{0}]", filenameWithoutPath1);
this.richTextBox1.Text = queryString;
string where = " WHERE BAR > 20.0";
string myquery = queryString + where;
// this.richTextBox1.Text = myquery;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(myquery, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string Query = "REPLACE INTO hp42mis.hydrodata (FILEMOD, DOEYMD,TIMEHMS,DATETIMEM,MARKER,CONTRACT_CODE,STS_00" +
",PIPE,PIPE_NO,STS_01,MAX_PRESB,STS_02,MIN_PRESSB,STS_03,TESTP_BAR,STS_04,five,STS_05,six,STS_06,seven,STS_07," +
"eight,STS_08,nine,STS_09) values ('" + newdate.ToString() + "',";
Query += "'" + Convert.ToDateTime(reader["Date"]).ToString("yyyy-MM-dd") + "'";
Query += ",'" + reader.GetValue(1).ToString() + "'";
Query += ",'" + Convert.ToDateTime(reader["Date"]).ToString("yyyy-MM-dd") + " " + reader.GetValue(1).ToString() + "'";
Query += ",'" + reader.GetValue(2).ToString() + "'";
Query += ",'" + reader.GetValue(3).ToString() + "'";
Query += ",'" + reader.GetValue(4).ToString() + "'";
Query += ",'" + reader.GetValue(5).ToString() + "'";
Query += ",'" + reader.GetValue(3).ToString() + "" + reader.GetValue(5).ToString() + "'";
Query += ",'" + reader.GetValue(6).ToString() + "'";
Query += ",'" + reader.GetValue(7).ToString() + "'";
Query += ",'" + reader.GetValue(8).ToString() + "'";
Query += ",'" + reader.GetValue(9).ToString() + "'";
Query += ",'" + reader.GetValue(10).ToString() + "'";
Query += ",'" + reader.GetValue(11).ToString() + "'";
Query += ",'" + reader.GetValue(12).ToString() + "'";
Query += ",'" + reader.GetValue(13).ToString() + "'";
Query += ",'" + reader.GetValue(14).ToString() + "'";
Query += ",'" + reader.GetValue(15).ToString() + "'";
Query += ",'" + reader.GetValue(16).ToString() + "'";
Query += ",'" + reader.GetValue(17).ToString() + "'";
Query += ",'" + reader.GetValue(18).ToString() + "'";
Query += ",'" + reader.GetValue(19).ToString() + "'";
Query += ",'" + reader.GetValue(20).ToString() + "'";
Query += ",'" + reader.GetValue(21).ToString() + "'";
Query += ",'" + reader.GetValue(22).ToString() + "'";
Query += ")";
MySqlCommand cmd = new MySqlCommand(Query, conne);
this.richTextBox1.Text = Query;
this.Refresh();
int res = 0;
try
{
res = cmd.ExecuteNonQuery();
}
catch (MySqlException Myex)
{
MessageBox.Show(Myex.Message);
}
rowcounter++;
this.rowcount.Text = rowcounter.ToString();
this.Refresh();
conne.Dispose();
conne.Close();
}
}
reader.Close();
connection.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

I found an easier way how to sort the array of files...
mFiles = System.IO.Directory.GetFiles(mDirectory, "*(WIDE).DBF");
Array.Sort(mFiles);

If you want to walk over your mFiles array based on each file's last write time, see Sort List using string without Linq:
private IList<string> GetOrderedFiles(string[] files)
{
var fileList = new List<string>(files);
Comparison<string> compare = delegate(string file1, string file2)
{
DateTime file1Time = File.GetLastWriteTime(file1);
DateTime file2Time = File.GetLastWriteTime(file2);
return file1Time.CompareTo(file2Time);
};
fileList.Sort(compare);
return fileList;
}
Usage:
var sortedFiles = GetOrderedFiles(mFiles);
foreach (string file in sortedFiles)
{
}

As others have said, that code needs reformatting and probably isn't even correct (e.g. you're setting mFiles within a loop iterating through mFiles).
However, maybe this will help?
Sorting Directory.GetFiles()
The key is using FileInfo items rather than just GetFiles().

You can do this :
public class ReverseComparer : IComparer<FileSystemInfo>
{
public int Compare(FileSystemInfo x, FileSystemInfo y)
{
return x.CreationTime.CompareTo(y);
}
}
DirectoryInfo di = new DirectoryInfo("C:\\...");
FileSystemInfo[] files = di.GetFileSystemInfos();
Array.Sort(files, new ReverseComparer());

Related

How to remove commas between a piped strings in a csv file in a eg |Ana "ana" Ana|, |adda,adda|

I am working on an ssis integration and wrote a script task in c# for automating my imports from csv file to my DBs. It works great but I need help with removing commas from strings in pipes(|aaa,aaa| or |a|,|a|) in the csv. For example "Address, city wide". I want a function that can remove that comma(,). I would paste a snippet of my code and what I have done so far.
#
region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
//using CsvHelper.Configuration;
#
endregion
namespace ST_7ce5ad6fbc104157b534f4eb484a4417 {
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain: Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase {
public void Main() {
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try {
//Declare Variables
string SourceFolderPath = Dts.Variables["User::SourceFolder"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
string ColumnsDataType = Dts.Variables["User::ColumnsDataType"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["moviesdb"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach(string fileName in fileEntries) {
//Writing Data of File Into Table
string TableName = "";
int counter = 0;
string line;
string ColumnList = "";
//MessageBox.Show(fileName);
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null) {
if (counter == 0) {
ColumnList = "[" + line.Replace("\"", "").Replace(FileDelimiter, "],[") + "]";
//MessageBox.Show(ColumnList);
//"[" + line.Replace(FileDelimiter, "],[") + "]";
TableName = (((fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")).Replace("\\", ""));
string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]')";
CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
CreateTableStatement += "([" + line.Replace("\"", "").Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
CreateTableCmd.ExecuteNonQuery();
//MessageBox.Show(CreateTableStatement);
} else {
string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
//query += "VALUES('" + line.Replace(FileDelimiter, "','").Replace("\"", "") + "')";
//query += "VALUES('" + line.Replace(FileDelimiter, "','").Replace("\"", "").Replace("\"'\"", "") + "')";
query += "VALUES('" + line.Replace("'", "").Replace(FileDelimiter, "','").Replace("\"", "") + "')";
// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
//move the file to archive folder after adding datetime to it
File.Move(fileName, ArchiveFolder + "\\" + (fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "") + "_" + datetime + FileExtension);
Dts.TaskResult = (int) ScriptResults.Success;
}
} catch (Exception exception) {
// Create Log File for Errors
using(StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() +
"\\" + "ErrorLog_" + datetime + ".log")) {
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int) ScriptResults.Failure;
}
}
}#
region ScriptResults declaration
enum ScriptResults {
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};#
endregion
}
}
It actually does what I want and imports successfully, but I need further assistance in tweaking the code to replace commas between strings in pipes in the csv file.

i am getting this error saving the data in Sql Server "conversion failed when converting date and/or time from character string.". below is my code:

string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.

c# get the DataType and Size of a column

public DataTable InsertToIncludeandReturnErrorTable(DataTable MappingTable, DataTable InsertTable, string TableName)
{
//split data and insert data to datatable and validation
var CS = Serenity.Data.SqlConnections.GetConnectionString("Northwind");
String MyConString = CS.ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = MyConString;
DataTable returnDataTable = InsertTable.Clone();
con.Open();
foreach (DataRow InsertRow in InsertTable.Rows)
{
try
{
string InsertDBFileld = "";
string DatarowField = "";
foreach (DataRow row in MappingTable.Rows)
{
if (InsertDBFileld == "")
InsertDBFileld = InsertDBFileld + row["TableColumn"].ToString().Replace("\r\n", "");
else
InsertDBFileld = InsertDBFileld + "," + row["TableColumn"].ToString().Replace("\r\n", "");
if (DatarowField == "")
DatarowField = "'" + DatarowField + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'";
else
DatarowField = DatarowField + ",'" + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'";
}
InsertDBFileld = InsertDBFileld + #",CreatedBy,CreatedDate,ModifiedBy,ModifiedDate";
DatarowField = DatarowField + ",'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'," + "'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'";
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO dbo." + TableName + #"(
" + InsertDBFileld + #"
) VALUES(" + DatarowField + ")", con))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
DataRow returnRow = InsertRow;
returnDataTable.Rows.Add(InsertRow.ItemArray);
}
}
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return returnDataTable;
}
[HttpGet]
public FileContentResult DownLoadFile(string destFilePath)
{
//Generate Excel file with data
destFilePath = destFilePath.Replace("%5c", "\\").Replace("%3a", ":");
byte[] fileBytes = System.IO.File.ReadAllBytes(destFilePath);
string fileName = "ErrorList.xlsx";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Orginal Code can detect the column data length and output wrong data row.
How can I get the DataType and Size of a column?
If I upload a excel exceed the data length, output a excel file and fill in the red color in the wrong data cell.
You can check the data type and maximum length from the columns of your DataTable:
Type columnType = InsertTable.Columns["TableColumn"].DataType;
int maxLength = InsertTable.Columns["TableColumn"].MaxLength;
If your table does not include schema information (which I doubt), you can get the schema first from the database with a SqlDataAdapter. The FillSchema method is what you need.

XSS and SQL Injection threats found by AppScan Source

So I have been given administration on a website that is basically a company conference room reservation system, it is connected to an access database for room details and vacancies. Problem is, AppScan source is showing a risk of XSS and SQL Injection. This is the complete function in where it is indicating the occurrence of these errors.
protected void btnReserve_Click(object sender, System.EventArgs e)
{
string start_slot, end_slot, event_desc, room_id, emp_nid;
string[] date;
start_slot = ddlStart.SelectedValue;
end_slot = ddlEnd.SelectedValue;
event_desc = txtEventDesc.Text;
room_id = Server.HtmlEncode(Request.QueryString["room_id"]);
emp_nid = Regex.Replace(Request.ServerVariables["LOGON_USER"], #"^.*\\(.*)$", "$1").ToUpper();
date = Request.QueryString["date"].Split('/');
DateTime dt = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
string sCmdCheckConflict = #"
SELECT count(*)
FROM t_msc_event
WHERE (event_date = #" +DateTime.Parse(Request.QueryString["date"]).ToString() + #"# )
AND (room_id = " + room_id + #") AND
(
(" + start_slot + #" BETWEEN start_slot AND end_slot) OR
(" + end_slot + #" BETWEEN start_slot AND end_slot) OR
(start_slot BETWEEN " + start_slot + #" AND " + end_slot + #") OR
(end_slot BETWEEN " + start_slot + #" AND " + end_slot + "))";
OleDbCommand cmdConflictCounter = new OleDbCommand(sCmdCheckConflict, cn);
int n;
int event_id;
try
{
cn.Open();
n = (int) cmdConflictCounter.ExecuteScalar();
string Msg;
if (n>0)
{
Msg = "<script language=javascript>alert('Chosen time is not possible due to a conflict.');</script>";
}
else
{
#region MS Access related region
OleDbCommand cmdgetMaxId = new OleDbCommand("select max(event_id) from t_msc_event", cn);
string sCmdInsert;
OleDbCommand cmdInsertEvent = null;
event_id = 0; bool success = false; int trials = 0;
do
{
try
{
event_id = (int) cmdgetMaxId.ExecuteScalar() + 1;
}
catch
{
event_id = 0;
}
sCmdInsert = #"
insert into t_msc_event (event_id,
emp_nid, event_desc, event_date,
start_slot, end_slot, room_id
) values (" + event_id + #",
'" + Server.HtmlEncode(emp_nid) + "', '" + Server.HtmlEncode(event_desc.Replace("'", "''")) + "', #" + dt.ToShortDateString() + "#, " +
start_slot + ", " + end_slot + ", " + room_id + ")";
cmdInsertEvent = new OleDbCommand(sCmdInsert, cn);
cmdInsertEvent.ExecuteNonQuery();
success = true;
} while ((!success) && (trials <=5));
OleDbDataAdapter daGetSlots = new OleDbDataAdapter("select slot_id, left(slot_desc,5) as slot_start, right(slot_desc,5) as slot_end from t_msc_slot order by slot_id", cn);
DataTable dtSlotInfo = new DataTable();
daGetSlots.Fill(dtSlotInfo);
OleDbCommand cmdGetRoolTitle = new OleDbCommand("select room_title from t_msc_room where room_id=" + Server.HtmlEncode(room_id), cn);
string room_title = (string) cmdGetRoolTitle.ExecuteScalar();
string msg = "Dear " + emp_nid +
",<br><br>This is to confirm your reservation of " +
room_title +
" on " + dt.ToShortDateString() + " from " +
dtSlotInfo.Rows[Convert.ToInt32(start_slot)]["slot_start"].ToString() + " to " +
dtSlotInfo.Rows[Convert.ToInt32(end_slot)]["slot_end"].ToString() + "." +
"<br><br>In case you want to cancel, go to " +
"<a href='" + Regex.Replace(Request.Url.ToString(), #"^(.*)/.*\.aspx\?*.*$", "$1/MyReservations.aspx") + "'>" +
"MS Conference Rooms Reservation -> MyReservatios</a>";
#endregion
string subject = "MS Conference Room Reservation Confirmation [id=" + event_id + "]";
try
{
SendEmail(emp_nid, subject, msg);
Msg = "<script language=javascript>alert('Room successfully reserved. You should receive a confirmation email shortly.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
catch
{
Msg = "<script language=javascript>alert('Room successfully reserved.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
}
Response.Write(Msg);
}
catch (Exception x)
{
Response.Write(x.ToString());
string Msg;
Msg = "<script language=javascript>alert('Error: " + x.ToString() + "');</script>";
Response.Write(Msg);
}
finally
{
cn.Close();
}
}
Sorry for having to show you the whole function as I have really no idea what I need to do here, this isn't my app.
what I did do is 1) Enable Request Validation in ASP.NET 2) encode user input by using Server.HtmlEncode(); but it is still reporting the same thing. Note that both start_slot and end_slot are DDLs so I thought I wouldn't need to encode/check them before sending. Would you please help me in modifying this code to neglect harmful user input? Thank you loads.
The correct way to use parameterized SQL query is
string commandText = "UPDATE ProductDetails
SET ProductQuantity = #quantity WHERE ProductId = #productId";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#productId", "P123");
command.Parameters.AddWithValue("#quantity", 10);
You can safely replace the "P123" with user provided input now.

Possible solution for locking the table in sqlserver using asp.net

I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.

Categories