Measure Response Time ASP.net - c#

I have an ASP Web Service (.asmx) which simply gets a SOAP Request with a query string, executes it on the database, and returns either the data, or the rows affected.
I want to log the response time it takes the server to reply in a Log Table on the Database, but I don't know how I can get the request and reply times, so I can calculate it. The way I did it now is it the WebMethod, I get the current time, then execute the query, and then get the timespan and save it on the DB. This does however not measure the serialization time it takes the server when it returns an object and serializes it in XML, so it is less than the actual response time. Here is my code:
[WebMethod]
public Table Select(string environment, string username, string password, string query)
{
DateTime start = DateTime.Now;
Table table = Methods.Select(environment, username, password, query);
string constring = ConfigurationManager.ConnectionStrings[environment].ConnectionString;
OracleConnection con = new OracleConnection(String.Format(ConfigurationManager.ConnectionStrings[environment].ConnectionString, username, password));
con.Open();
TimeSpan time = DateTime.Now - start;
OracleCommand cmd = new OracleCommand("INSERT INTO WS_REQUESTS VALUES (TIMESTAMP'" + start.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', '" + username + "', '" + query + "', " + time.TotalMilliseconds + ", " + errorflag + ", '" + message + "')", con);
int rows = cmd.ExecuteNonQuery();
con.Close();
return table;
}
The Table is a DTO I created for the data, and Methods is the class where I have the query functions.
Can anyone tell me how can I measure the response time as accurate as possible? The best would be as simple as possible, with code inside my service, at most something I can embed in my service, so that it is standalone, and not additional performance measuring tools I need to install on my server. Thanks.

Related

Add date to sqlserver in yyyy-mm-dd

When i add the lastImportedDate(dd-mm-yyyy) with the following method to the sql server everything is fine. In the database the date is yyyy-mm-dd
But add the lastImportedDate(dd-mm-yyyy) with a different pc on the same server the day and month are switched. In the database the date is yyyy-dd-mm.
internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, string periodStart, string periodEnd)
{
// Create SQL connection #connection
SqlConnection sqlConnection1 = new SqlConnection(Connection.connectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string periodstartQuery = periodStart;
string periodEndQuery = periodEnd;
// Create query with values and execute query
if (!periodStart.Equals("NULL"))
{
periodstartQuery = " '" + periodStart + "'";
}
if (!periodEnd.Equals("NULL"))
{
periodEndQuery = " '" + periodEnd + "'";
}
cmd.CommandText = "Insert into CarsSellout (CustomerID, type, lastImportedDate, PeriodStart, PeriodEnd) VALUES ('" + CustomerID + "', '" + type + "', '" + lastImported + "', " + periodstartQuery + ", " + periodEndQuery + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
Note that the date settings on the pc's are both set as dd-mm-yyyy.
if you need more info please add a comment.!
What can be the problem in this case?
Do not insert your DateTime values with their string representations. Add your DateTime values directly to your parameterized queries.
SQL Server keeps your DateTime values in a binary format. They didn't have any format or something. What you saw them as yyyy-MM-dd or dd-MM-yyyy are just their textual representations.
Generating different string representations of a DateTime instance for different servers usually because they use different culture settings. But since you didn't show any relevant code that generates your strings, we never know.
Speaking of, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Please read carefully;
Bad habits to kick : choosing the wrong data type
As a best practice, use using statement to dispose your connections and commands automatically instead of calling Close methods manually.
using(var con = new SqlConnection(conString))
using(var cmd = con.CrateCommand())
{
// Define your CommandText with parameterized query.
// Define your parameters and their values. Add them with Add method to your command
// Open your connection
// Execute your query
}

Update database with date format

I found some threads here in the forum related to this problem but they didn't help me. I just want to update my database with a date value. These come from a Textfile (written there as 2014-10-02 for example). Now I tried this (which was mentioned in the other threads):
String connectionQuery = form1.conString.Text;
SqlConnection connection = new SqlConnection(connectionQuery);
SqlCommand sqlComInsert = new SqlCommand(#"INSERT INTO [" + form1.tableName.Text + "] ([" + form1.CusId.Text + "],["+ form1.date.Text +"],[" + form1.cusName.Text + "]) VALUES('" + cusId[i] + "',convert(date,'" + date[i] + "',104),'" + "','" + cusName[i] + "')", connection);
sqlComInsert.Connection.Open();
sqlComInsert.ExecuteNonQuery();
sqlComInsert.Connection.Close();
Now when I leave the "'" out ("',convert / "',104)) he tells me that the syntax is incorrect near 2013 (the beginning of my date). When I write it like above then I get:
String or binary data would be truncated.
What is this? I tried also to convert the date with:
for (int i = 0; i < typeDelDate.Count; i++)
{
unFormatedDate = date[i];
formatedDate = unFormatedDate.ToString("dd/MM/yyyy");
dateFormat.Add(formatedDate);
}
but I get still the same errors. How can I update my values? the column type is "date".
Use parametrized queries instead of slapping strings together:
var commandText = "insert (column) values (#dt);";
var cmd = new SqlCommand(commandText, connection);
cmd.Parameters.AddWithValue("dt", DateTime.ParseExact(dateString, "yyyy-MM-dd"));
cmd.ExecuteNonQuery();
Do not pass values into queries by adding strings - if possible, you should always use parameters. It saves you a lot of trouble converting to proper values (different for different locales etc.), it's more secure, and it helps performance.

Storing Data in SQLite

Is there a way to store TEXT in SQLite database without SQLite trying to parse it?
Ran into a problem where when you store TEXT that is similar to SQLite query, it tries to parse it for some reason.
Query I use to save TEXT: "insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".
Similar text I'm trying to save: "SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".
When i try to save something like that, it says: Error: SQL logic error or missing database near "table":syntax error
Please note that values (name, currentDate, reminder, content) are not hard coded, they are passed as strings. actual code is like below:
SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);
Thanks for any input.
As I suspect, the problem is that you're putting your values directly into the SQL - without even trying to escape them. Don't do that. As well as the problems you're seeing, you've opened yourself up to a SQL injection attack. Use parameterized SQL instead, and specify values for the parameters.
For example:
// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
" (Name, DateCreated, Reminder, Content) values " +
"(#Name, #DateCreated, #Reminder, #Content)");
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.Add("#Name", SQLiteType.Text).Value = noteName;
command.Parameters.Add("#DateCreated", SQLiteType.DateTime).Value = currentDate;
command.Parameters.Add("#Reminder", SQLiteType.Text).Value = reminder;
command.Parameters.Add("#Content", SQLiteType.Text).Value = content;
command.ExecuteNonQuery();
}

Update DATETIME column where said DATETIME < current DATETIME

I've got an ASP.NET 4.0 C# web application that allows multiple users to update rows in the SQL Server DB at the same time. I'm trying to come up with a quick system that will stop USER1 from updating a row that USER2 updated since USER1's last page refresh.
The problem I'm having is that my web application always updates the row, even when I think it shouldn't. But when I manually run the query it only updates when I think it should.
This is my SQL query in C#:
SQLString = "update statuses set stat = '" + UpdaterDD.SelectedValue +
"', tester = '" + Session["Username"].ToString() +
"', timestamp_m = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
"' where id IN (" + IDs + ") and timestamp_m < '" + PageLoadTime + "';";
And here's a 'real world' example:
SQLString = "update statuses set stat = 'PASS', tester = 'tester007',
timestamp_m = '2013-01-23 14:20:07.221' where id IN (122645) and
timestamp_m < '2013-01-23 14:20:06.164';"
My idea was that this will only update if no other user has changed this row since the user last loaded the page. I have formatted PageLoadTime to the same formatting as my SQL Server DB, as you can see with DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), but something still isn't right.
Does anyone know why I get two different results? Is what I want to do even possible?
I really think the problem is that the page load time is not being set correctly, or is being set immediately before the DB call. For debugging, you may try hardcoding values into it that you know will allow or disallow the insert.
Here's a parameterized version of what you have. I also am letting the DB server set the timestamp to its current time instead of passing a value. If your DB server and your Web server may not have their time of day in synch, then set it yourself.
Using parameterization, you don't have to worry about whether the date/time format is correct or not. I don't know what the DB types are of stat, tester, and timestamp_m so adding the parameter DB type may need adjusting.
string sql = "update statuses set stat = #stat, tester = #tester" +
", timestamp_m = getdate()" +
" where id IN (" + IDs + ") and timestamp_m < #pageLoadTime";
SQLConnection conn = getMeASqlConnection();
SQLCommand cmd = new SQLCommand(sql, conn);
cmd.Parameters.Add("#stat", System.Data.SqlDbType.NVarChar).Value = UpdaterDD.SelectedValue;
cmd.Parameters.Add("#tester", System.Data.SqlDbType.NVarChar).Value = Session["Username"].ToString();
// Here, pageLoadTime is a DateTime object, not a string
cmd.Parameters.Add("#pageLoadTime", System.Data.SqlDbType.DateTime).Value = pageLoadTime;

insert date into SQL

I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.
Conversion failed when converting date and/or time from character string.
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";
Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:
using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = new SqlCommand(conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, developerID, publisherID, consoleID) VALUES (#gameName, #genreID, #players, #online, #dateReleased, #developerID, #publisherID, #consoleID)";
cmd.Parameters.AddWithValue("#gameName", GameNameTxt.Text);
cmd.Parameters.AddWithValue("#genreID", GenreCombo.SelectedValue);
cmd.Parameters.AddWithValue("#players", PlayersNUD.Value);
cmd.Parameters.AddWithValue("#online", OnlineCombo.SelectedText);
cmd.Parameters.AddWithValue("#dateReleased", DateReleasedDate.Value);
cmd.Parameters.AddWithValue("#developerID", DeveloperCombo.SelectedValue);
cmd.Parameters.AddWithValue("#publisherID", PublisherCombo.SelectedValue);
cmd.Parameters.AddWithValue("#consoleID", ConsoleCombo.SelectedValue);
var result = cmd.ExecuteNonQuery();
...
}
As far as the dateAdded column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.
Notice how you are directly passing DateTime instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.
DateReleasedDate.Value.ToString("yyyy-MM-dd");
The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.
The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.
The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.
Some info for you: ToOADate

Categories