Website's performance issue - asp.net

I have an Asp.Net website with one web page whose sole purpose is receiving data in the form of a query string then separate it as required and store this data to the database.
This data comes from several Vehicle Tracking Systems. Each vehicle sends a string of data as query string every 30 seconds.
I have written the code in my webpage in such a way that as the webpage is accessed, in the page load, I read the query string and do the insert operation into the database. Something like this-
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
string input = Request.QueryString["vinput"];
var m = Regex.Match(input, #"~(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#");
if (m.Success)
{
string[] vals = new string[20];
int j = 1;
for (int i = 0; i < 20; i++)
{
vals[i] = m.Groups[j].Value;
j++;
}
cmd.CommandText = "insert into tracking (vehicle_no,hardware_id,lat,lng,speed,direction,an0,an1,an2,an3,di0,di1,di2,di3,do0,do1,do2,do3,tdate,ttime) values('" + vals[0] + "','" + vals[1] + "','" + vals[2] + "','" + vals[3] + "','" + vals[4] + "','" + vals[5] + "','" + vals[6] + "','" + vals[7] + "','" + vals[8] + "','" + vals[9] + "','" + vals[10] + "','" + vals[11] + "','" + vals[12] + "','" + vals[13] + "','" + vals[14] + "','" + vals[15] + "','" + vals[16] + "','" + vals[17] + "','" + vals[18] + "','" + vals[19] + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
I created a simulator app for testing this site in place of vehicle tracking systems. This site works fine when there is data coming from one to three simulator instances, but fails to save data to database when more than 3 simulator instances send data simultaneously(Approximately).
For example, I am sending 5 records, each one at a time from the simulator and 6 such simulator instances sending data to the page. At the end in the database I see only 15 records inserted instead of 30 records. By the way this website runs in IIS 5.1.
How do I deal with this issue? Suggestions please.
UPDATE: Finally found the issue. After a lot of googling found this link and this. Its with the server, since the request limit is only 3 for basic/starter in windows xp IIS.

No point in using a Page when you can use something lighter weight like a handler. You can switch a few things around, but this is not a heavy operation. Here's a pretty optimal way to do it with one exception and that would be to make a stored procedure rather than generating an insert statement from a string:
public class htest : System.Web.IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(System.Web.HttpContext context)
{
System.Web.HttpRequest Request = context.Request;
Match m = Regex.Match(Request.QueryString["vinput"], #"~(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#");
if (m.Success)
{
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection())
{
try
{
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("command", con);
string[] vals = new string[20];
int j = 1;
for (int i = 0; i < 20; i++)
{
vals[i] = m.Groups[j].Value;
j++;
}
cmd.CommandText = "insert into tracking (vehicle_no,hardware_id,lat,lng,speed,direction,an0,an1,an2,an3,di0,di1,di2,di3,do0,do1,do2,do3,tdate,ttime) values('" + vals[0] + "','" + vals[1] + "','" + vals[2] + "','" + vals[3] + "','" + vals[4] + "','" + vals[5] + "','" + vals[6] + "','" + vals[7] + "','" + vals[8] + "','" + vals[9] + "','" + vals[10] + "','" + vals[11] + "','" + vals[12] + "','" + vals[13] + "','" + vals[14] + "','" + vals[15] + "','" + vals[16] + "','" + vals[17] + "','" + vals[18] + "','" + vals[19] + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
catch
{
//At least do some type of logging in this event.
}
finally
{
con.Close();
}
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("Success");
}
}
Obviously you can use some boolean values to determine what you write back to the client at the end.

few suggestions..
You are opening connection. please close it at bottom as well. Dispose cmd object as well.
Put your INSERT Ststement into a SQL Transcation
USe try and Catch (USe the Catch clause to store error messages into Database , ex.message returns error detail.)

Related

copy from html form and paste on outlook

I want to build an application in which when I fill up a form it will copy the data and on a button click it will paste some of the data in outlook email body
Thanks
I am about to finish my webform site
Issue : when I add small content (any type) to textarea and click on submit , it works !
But when i enter long multi line text in textarea it give me syntax error near s.
SqlConnection con = new SqlConnection("Data source=hidden; initial catalog=dsatdata; User id=sa; password=xxxxxx");
con.Open();
var query = "insert into escalationmatrix values ('" + lbl_case_number.Text + "','" + Request.Form["statust"].ToString() + "','" + Request.Form["status_summaryt"].ToString() + "', '" + Request.Form["impact_severityt"].ToString() + "', '" + Request.Form["next_stept"] + "', '" + Request.Form["root_causet"] + "','" + DateTime.Now + "')";
// SqlCommand cmd = new SqlCommand("UPDATE [escalation] SET [Status] = '" + Request.Form["statust"].ToString() + "', [status_summary] = '" + Request.Form["status_summaryt"].ToString() + "', [impact_severity] = '" + Request.Form["impact_severityt"].ToString() + "', [next_step] = '" + Request.Form["next_stept"] + "', [root_cause] = '" + Request.Form["root_causet"] + "' WHERE [Case_Number] = '" + lbl_case_number.Text + "'" , con);
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();`

Please Verify My ASP.NET Code to insert data to oracle database

No matter what I do the following code does not seem to work. It always breaks at ExecuteNonQuery().
Anything I am missiong?
Always throws
System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
OracleConnection conn = new OracleConnection(connectionString);
int room_id = Int32.Parse(DropDownList2.SelectedValue);
int activity_id = Int32.Parse(DropDownList1.SelectedValue);
string session_code = TextBox1.Text;
int start_time = GetTimeSeconds(startTime.Text);
int period = GetTimeSeconds(duration.Text);
string book_date = bookDate.Text;
string ref_no = DropDownList3.SelectedValue;
conn.Open();
using (OracleCommand cmd = new OracleCommand(
"insert into BRAZESH.ALL_SESSION(SESSION_CODE,START_TIME,\"PERIOD\",BOOKED_DATE,ROOM_ID,ACTIVITY_ID,REF_NO)" +
" values ('" + session_code + "'," + start_time + "," + period + ",to_date('" + book_date + "', 'yyyy-mm-dd')," + room_id + "," + activity_id + ", '" + ref_no + "')"))
{
try
{
cmd.ExecuteNonQuery();
}catch (OracleException ex)
{
throw ex;
}
}
}
}
You are not using conn while defining the connection to be used by the command. use the following line. Read details on usage here
using (OracleCommand cmd = new OracleCommand(
"insert into BRAZESH.ALL_SESSION(SESSION_CODE,START_TIME,\"PERIOD\",BOOKED_DATE,ROOM_ID,ACTIVITY_ID,REF_NO)" +
" values ('" + session_code + "'," + start_time + "," + period + ",to_date('" + book_date + "', 'yyyy-mm-dd')," + room_id + "," + activity_id + ", '" + ref_no + "')",conn))

Serversided code for updating?

I have a website that when you fill in information and push on a submit button, button1_click() inserts data into the database. I have another button that generates an id that gets the date and '0001' after it and fills it into the textbox. How do I use serverside code to have my functions check to see if it has the 0001 in the database, and if it's in the database make it put in '0002' instead? I know I need to use parameters but I'm confused about how that works and the code used to update the database.. here is my code
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into John_IEP_Crossing_Dock_Shipment values('" + generateidtxt.Text + "','" + hawbtxt.Text + "','" + invrefpotxt.Text + "','" + hppartnumtxt.Text + "','" + iecpartnumtxt.Text + "','" + qtytxt.Text + "','" + bulkstxt.Text + "','" + boxplttxt.Text + "','" + rcvddatetxt.Text + "','" + statustxt.Text + "','" + carriertxt.Text + "','" + shippertxt.Text + "', '', '','','','','',GETDATE(),GETDATE())", con);
cmd.ExecuteNonQuery();
con.Close();
generateidtxt.Text = "";
hawbtxt.Text = "";
invrefpotxt.Text = "";
hppartnumtxt.Text = "";
iecpartnumtxt.Text = "";
qtytxt.Text = "";
bulkstxt.Text = "";
boxplttxt.Text = "";
rcvddatetxt.Text = "";
statustxt.Text = "";
carriertxt.Text = "";
shippertxt.Text = "";
con.Dispose();
}
protected void generateid_Click(object sender, EventArgs e)
{
generateidtxt.Text = "from DB";
}
}
here is the sql commands I think I need to use..
insert John_IEP_Crossing_Dock_Shipment (ID)
select ID = Left(max(ID),10) + '-' + RIGHT('000' + convert(varchar,convert(int,right(max(ID),4)) + 1), 4)
from John_IEP_Crossing_Dock_Shipment
where Left(ID,10) = convert(varchar(10), Getdate(),20)
select ID = Left(max(ID),10) + '-' + RIGHT('000' + convert(varchar,convert(int,right(max(ID),4)) + 1), 4)
from John_IEP_Crossing_Dock_Shipment
where Left(ID,10) = convert(varchar(10), Getdate(),20)
If I'm understanding what you're asking correctly, do you mean you want to get a value from the newly inserted record and check its value?
If so, you can use ##IDENTITY which will give you the id of the last record inserted into the database from which you can run a SELECT statement and retrieve the data you need for applying your check.
Please refer to the following link for more information:
http://msdn.microsoft.com/en-us/library/ms187342.aspx

System.Data.SqlClient.SqlException: Incorrect syntax near ''

cmd.Connection = con;
con.Open();
cmd.CommandText = "Update tiit.Enquiry Set Status='" + DropDownList4.SelectedValue + "', NextFollowup='" + TextBox8.Text + "', Remarks='" + TextBox9.Text + "', Name='" + TextBox1.Text + "', Email='" + TextBox2.Text + "', Phone='" + TextBox3.Text + "','','','','', City='" + TextBox4.Text + "', Country='" + TextBox5.Text + "', Course='" + TextBox6.Text + "', Comments='" + TextBox7.Text + "', Cost='" +TextBox14.Text+ "' where SN='" + HiddenField1.Value + "'";
int i = cmd.ExecuteNonQuery();
con.Close();
No, don't do this. Never use string concatenations (+ operator) when building your SQL queries. Use parametrized queries:
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE tiit.Enquiry Set Status=#Status, NextFollowup=#NextFollowup, ...";
cmd.Parameters.AddWithValue("#Status", DropDownList4.SelectedValue);
cmd.Parameters.AddWithValue("#NextFollowup", TextBox8.Text);
...
This way your code won't be vulnerable to SQL injection and you won't have any encoding problems.
In all probability this:
"Update tiit.Enquiry Set Status='"
is you problem. (I'm talking about the .)
I completely agree however - use parametrised queries.

How to connect mysql to DevExpress ASPxScheduler without SqlDataSource

I have an ASP.net project I'm looking at and they want to use MySQL. I'm used to SQL server but using mySQL shouldn't be a problem.
Normally the control would like a SqlDataSource to bind to but that's not available with MySQL (from other posts on this site).
What's the best way to connect MySQL and the DevExpress ASPxScheduler so that you can create appointments?
Why not an ObjectDataSource and write the data layer? Or use LLBLGen, I think it works just fine with MySQL. The one caveat I've seen is that the MySQL ODBC and ADO drivers have issues with metadata.
I did end up using the objectdatasource and the ObjectCreated method and wrote the datalayer to insert records into the mysql database. I've included my code just incase someone needs some help with some of the logic.
protected void appointmentsDataSource_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = new CustomEventDataSource(GetCustomEvents());
}
public void InsertAppointment()
{
//need to reformat the dates
string tempStartDate;
string tempStartMinutes;
if (appointmentobject.Start.Minute.ToString().Length == 1)
{
tempStartMinutes = "0" + appointmentobject.Start.Minute.ToString();
}
else
{
tempStartMinutes = appointmentobject.Start.Minute.ToString();
}
tempStartDate = AppointmentObject.Start.Year + "-"
+ AppointmentObject.Start.Month + "-"
+ appointmentobject.Start.Day + " "
+ appointmentobject.Start.Hour + ":"
+ tempStartMinutes;
string tempEndDate;
string tempEndMinutes;
if (appointmentobject.End.Minute.ToString().Length == 1)
{
tempEndMinutes = "0" + appointmentobject.End.Minute.ToString();
}
else
{
tempEndMinutes = appointmentobject.End.Minute.ToString();
}
tempEndDate = AppointmentObject.End.Year + "-"
+ AppointmentObject.End.Month + "-"
+ appointmentobject.End.Day + " "
+ appointmentobject.End.Hour + ":"
+ tempEndMinutes;
//TODO Add CustomField : Need to add to this Insert Statement
//Change the appointment subject
string NewSubject = AppointmentObject.CustomFields["fldFirstName"]
+ ", " + AppointmentObject.CustomFields["fldLastName"]
+ ", " + AppointmentObject.CustomFields["fldClassID"]
+ ", " + AppointmentObject.CustomFields["fldPhoneNumberDay"];
string mySQLQueryString = #"INSERT INTO appointment (StartDate,EndDate,Subject,Status,Description,label,location,Type,FirstName,
LastName,PhoneNumberDay,PhoneNumberEvening,DriversLicenseNumber,Email,RentalCar,Payment,ConfirmationNumber,
PermitNumber,ClassID,CreateDate,CreateUser,NoticeToReport)
VALUES('" + tempStartDate + "','"
+ tempEndDate + "', '"
//+ AppointmentObject.Subject + "',"
+ NewSubject + "',"
+ AppointmentObject.StatusId + ",'"
+ AppointmentObject.Description + "',"
+ AppointmentObject.LabelId + ", '"
+ AppointmentObject.Location + "',"
+ "0, '" //type
+ AppointmentObject.CustomFields["fldFirstName"] + "','"
+ AppointmentObject.CustomFields["fldLastName"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberDay"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberEvening"] + "','"
+ AppointmentObject.CustomFields["fldDriversLicenseNumber"] + "','"
+ AppointmentObject.CustomFields["fldEmail"] + "',"
+ AppointmentObject.CustomFields["fldRentalCar"] + ","
+ AppointmentObject.CustomFields["fldPayment"] + ",'"
+ AppointmentObject.CustomFields["fldConfirmationNumber"] + "','"
+ AppointmentObject.CustomFields["fldPermitNumber"] + "',"
+ AppointmentObject.CustomFields["fldClassID"] + ", '"
//ignore create date for now.
//+ AppointmentObject.CustomFields["fldCreateDate"] + "', '"
+ "2009-01-01 12:00', '"
+ AppointmentObject.CustomFields["fldCreateUser"] + "', "
+ AppointmentObject.CustomFields["fldNoticeToReport"] + ")";
MySqlConnections test = new MySqlConnections();
test.InsertRow(mySQLQueryString);
}
public class MySqlConnections
{
private static string DriverConnectionString = "Database=driverexam;Data Source=localhost;User Id=ART;Password=art01";
public DataSet SelectRows(DataSet dataset, string query, string tablename)
{
MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, conn);
adapter.Fill(dataset, tablename);
conn.Close();
return dataset;
}
public bool InsertRow(string query)
{
// MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlConnection conn = new MySqlConnection();
MySqlCommand cmd = new MySqlCommand();
conn.ConnectionString = DriverConnectionString;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Success Occurred ");
} //end of try
catch(Exception ex)
{
Console.WriteLine("Error Occurred - " + ex.Message);
}
return true;
}
}

Resources