Converting Request.QueryString to integer - c#

How do i convert a Request.Query string to an integer value. I've tried all the Convert.ToInt32 and Int32.Parse but it says Input string is not in the correct format. I am using the string value as an input to a stored procedure which takes in only integer types for that field.
Here's a part of the code-
string rid=Request.QueryString["RID"];
lblRID.Text = rid;
int id= Int32.Parse(rid);
if (lblRID.Text!= null)
SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection);
myCommand.Parameters.AddWithValue("#RID",id); //RID is int in database and stored procedure
myCommand.CommandType = CommandType.StoredProcedure;

int foo;
int.TryParse(Request.QueryString["foo"], out foo);
or just like you say, int.Parse should convert to int
Could you post some code here ?

The answer thesedays varies based on what framework you're using as msft has made query params part of the view attribute model now for binding (ref: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromqueryattribute?view=aspnetcore-3.1).
You can still access most things via httpcontext for the sake of example.
var fooIsInt = int.TryParse(HttpContext.Request.Query["foo"], out var foo);
Original Example for webforms in .net 2.0
Quick and dirty (and in a page load because this is an example, you should be able to work out what's happening from this)
<script runat="server">
private void Page_Load(object sender, System.EventArgs e){
string test = Request.QueryString["foo"];
//Convert the query string you captured to an int and store it in an int.
int intTest = Convert.ToInt32(test);
Response.Write(intTest.GetType() + "<br>" + intTest);
}
</script>

How about looking on the input that you provide to Int32.Parse?

We use a base class from which every Page inherits. We have the following method that returns integer values from querystring params:
protected int FetchQueryStringIdentifierByKey(string key)
{
int identifier;
var isInt = int.TryParse(Request.QueryString[key], out identifier);
return (isInt) ? identifier : 0;
}
Credit goes to Jayson Knight for his research into his original bench-marking results under .NET 2.0.

string id = Request.QueryString["RID"].ToString();
userid=Convert.ToInt32(id);

How about using TryParse like this:
string rid = Request.QueryString["RID"];
int id = 0;
if (!string.IsNullOrEmpty(rid) && Int32.TryParse(rid, out id))
{
lblRID.Text = rid;
SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection);
myCommand.Parameters.AddWithValue("#RID",id);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Execute...
}

The problem is that the value passed in the query string with the RID parameter is not a number, so it cant be parsed to an int. E.g you have ?RID=hello or maybe no RID parameter at all (in which case the value is null). Inspect the querystring to see the actual value passed.

Related

How can convert DBObject value into long

I want to convert DBObject value into long. I have value in db something like id = 24100001000001.
I'm using this code:
String totalcount = "SELECT MAX(id) FROM table";
SqlCommand cmd1 = new SqlCommand(totalcount, con);
cmd1.ExecuteNonQuery();
long count = (long)(cmd1.ExecuteScalar());
Using this code, I'm getting an error:
System.InvalidCastException: sSpecified cast is not valid.
at Default.method1(Object sender, EventArgs e) in c:\Users\aBhiShEkrANAa\Desktop\ABC\Prroject\Default.aspx.cs:line 43
I just want this id value into long.
Little bit simpler approach will be to use right type for the job:
var value = (long?)command.ExecuteScalar();
If you want to return default value instead of nullable:
var value = (long?)command.ExecuteScalar();
return value.GetValueOrDefault();
Nullable value will handle DbNull and using nullable will provide more information for other developers/readers.
Notice that actual value under object returned by ExecuteScalar is a long, using Convert.ToInt64 will be much overhead, because converting do much more work.
It might contain Null values. So it would be better to use Convert instead of cast in this case, or even would be better to use something like this:
var temp = cmd1.ExecuteScalar();
temp = (temp == DBNull.Value) ? null : temp;
long count = Convert.ToInt64(temp);

Out string parameter in C#

I have this method:
public static int ExecuteNonQuery(ref DbCommand command, out string ErrorMessage)
{
ErrorMessage = String.Empty;
DbTransaction tran = null;
DbConnection conn = null;
int result = 0;
This method is used when accessed on another page. I pass a command in the form of SQLcommand to which I pass a query, but I don't get what this out string is for. This is someone else's code, but I want to use it for abstraction purposes of insertion queries. How should I get the errormessage parameter as it says it's an out string.
I want to do like this on one of my pages:
string Email = "example#example.com";
string Password = "Hello";
SqlCommand command = new SqlCommand("insert into J_example_Tbl(J_example_Email,J_example_Password) VALUES('"+Email+"','"+Password+"')");
PrimaryDBClass.ExecuteNonQuery(command, "Should I do like this");
Regarding
but I don't get what this out string is for
Out is stands for pointing to a variable. The out keyword describes parameters whose actual variable locations are copied onto the stack of the called method, where those same locations can be rewritten. This means that the calling method will access to the changed parameter.
For example: If you declare a variable named test in class1 and want to change the value from another class, class2, and still want to get the changed value from class1 you have to send the test variable with the out keyword from class1 to class2.
Which means in your method:
public static int ExecuteNonQuery(ref DbCommand command, out string ErrorMessage)
If any change occurred in variable ErrorMessage it will point to the actual variable where from it comes. So you will get the changed value from outside of the method ExecuteNonQuery().
The out parameter can be used like this:
string Email = "example#example.com";
string Password = "Hello";
SqlCommand command = new SqlCommand("insert into J_example_Tbl(J_example_Email,J_example_Password) VALUES('"+Email+"','"+Password+"')");
string error;
PrimaryDBClass.ExecuteNonQuery(command, out error);
if(error != null)
....
You should probably check for the result in some other way (like checking the return value or something). Look at Jon Skeet's suggestions as well.

int does not contain a constructor that takes 1 arguments

Hey guys this bug has been puzzling me for like 4 hours, and nothing I've tried works.
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int.ToString());
id.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(id);
cmd.ExecuteNonQuery();
book.BookId = new int(id.Value.ToString()); // <------ERROR
The error is:
int does not contain a constructor that takes 1 arguments
Here are some of the other things I have tried:
int x = id.value.ToString();
int xi = Convert.ToInt32(x);
book.BookId = x;
Maybe this one?
book.BookId = Int32.Parse(id.Value.ToString());
Since none of the answers so far have actually explained what you are doing wrong - this occurs because you are trying to call a constructor of int and pass an argument. As you can see here, there is no int constructor that accepts a string argument (or any other type, for that matter).
There are a few ways of converting a string to an integer, but the most robust (as already posted by Thomas) is to use Int32.TryParse.
If you are 100% sure that your string contain an integer and you are ok with throwing an exception else, you can do :
string id = "55";
int x = Int32.Parse(id);
Else, cleaner you can manage the case where the string is not an integer :
string id = "55";
int x = 0;
if(!Int32.TryParse(id, out x))
{
//Manage the special case here where id is not a int
}
Try this
book.BookId = Convert.ToInt32(id.Value);
You have to try any of this:
book.BookId = Int32.Parse(id.Value.ToString());
OR
book.BookId = (int)id.Value.ToString();
OR
book.BookId = int.Parse(id.Value.ToString());
You must check to make sure that id.Value is not NULL. After you've made sure, then this should work:
book.BookId = Convert.ToInt32(id.Value);
or even
book.BookId = (int) id.Value;
Edit
If Int32.Parse() is throwing a format exception, you must be giving it something that is not an integer. You say you're confident that it's not NULL, so what is it?
From my point of view you are using ToString() to much. Try this:
SqlParameter id = new SqlParameter("#bookId", System.Data.SqlDbType.Int);
id.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(id);
cmd.ExecuteNonQuery();
Int32.TryParse(id.Value.ToString(),out book.BookId);
This statement doesn't look correct
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int.ToString());
I think you should change it either Int or String
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int);
Just change your statement
book.BookId = Convert.ToInt32(id.Value.ToString());

C# SqlParameters Short Hand

I'm taking data that is in a List of Record objects and putting their contents in to a database:
// Processes a Record and adds it to the database
public bool addRecord(SqlConnection db, List<Record> recordsToAdd)
{
using (SqlCommand command = db.CreateCommand())
{
foreach (Record record in recordsToAdd)
{
// Set the query command text
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER (PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC) VALUES ('#PRODCODE', '#TOTFREE', '#TOTPHYS', '#ITEMTYPE', '#PRODESC')";
SqlParameter param1 = new SqlParameter("#CURSTAT", record.curstat);
SqlParameter param2 = new SqlParameter("#ITEMDESC", record.itemdesc);
SqlParameter param3 = new SqlParameter("#PRODCODE", record.prodcode);
SqlParameter param4 = new SqlParameter("#TOTFREE", record.totfree);
SqlParameter param5 = new SqlParameter("#TOTPHYS", record.totphys);
SqlParameter param6 = new SqlParameter("#ITEMTYPE", record.itemtype);
SqlParameter param7 = new SqlParameter("#PRODESC", record.proddesc);
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
command.Parameters.Add(param4);
command.Parameters.Add(param5);
command.Parameters.Add(param6);
command.Parameters.Add(param7);
// Execute the query
command.ExecuteNonQuery();
}
return true;
}
}
Here's my Record class:
class Record
{
public string curstat { get; set; }
public string itemtype { get; set; }
public string itemdesc { get; set; }
public string prodcode { get; set; }
public string proddesc { get; set; }
public string totfree { get; set; }
public string totphys { get; set; }
}
Just from looking at the code, I've got a feeling that there is a shorter way of achieving this.
But secondly, I'm not even sure if I've done it correctly that the #PARAMETER values are being replaced.
If I view the contents of command, it still shows the query string with the # parameters.
Also, I'm getting this error on command.ExecuteNonQuery():
String or binary data would be truncated.
The statement has been terminated.
So, my questions are:
Is there a shorter way to set and add multiple parameters to the query?
What could be causing the error?
You have a bigger constructor:
command.Parameters.Add(
"#CategoryName", SqlDbType.VarChar, 80).Value = "toasters";
Using the method AddWithValue will make the code a little bit shorter:
command.Parameters.AddWithValue("#CURSTAT", record.curstat);
//...
I do it a bit differntly.
I have both a extension method and a static method to create SqlParameters.
public static SqlParameter ToParam(this object v,string name){
return new SqlParameter(name,v);
}
Then I do something like this:
var p = new List<SqlParameter>();
p.Add(record.curstat.ToParam("#curstat"));
p.Add(record.itemdesc.ToParam("#itemdesc"));
//etc...
command.Parameters.AddRange(p.ToList());
The String or binary data would be truncated. most likely means your putting too many characters into one of your VARCHAR fields. I.e., if your column PRODDESC is a VARCHAR(50), and the string you're trying to insert is 70 characters, you will see that error.
Others have addressed alternative ways of doing the parameters so you can reduce the lines of code.
For a shorter syntax, you can use AddRange method of the SqlParameterCollection class. It means:
command.Parameters.AddRange(new [] {
new SqlParameter(...),
new SqlParameter(...),
new SqlParameter(...) });
The error you're getting indicates that a string value doesn't fit in the table column or parameter, and is being truncated. You should check the length of the column in comparison to the data being inserted, or specify the length of parameters using another overload of the SqlParameter constructor.
If you wanted to use the following class:
Class MyParam
{
public string name {get;set;}
public object value {get;set;}
}
then you could have a List called myParams and do:
foreach(var p in myParams) command.Parameters.AddWithValue(p.name, p.value);
You obviously have to link the parameters and values somehow and there's no way around that. But if you do it in a class like this then the code that actually does the action is only one line long.
I think the message
String or binary data would be truncated.
The statement has been terminated.
comes from an error in your Command Text: in the SQL Query the parameters, even if they are strings, do not need to be quoted.
Replace the command with this
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER
(PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC)
VALUES (#PRODCODE, #TOTFREE, #TOTPHYS, #ITEMTYPE, #PRODESC)";
To shorten the code i think you could add somewhere (for example in your record class or in an helper class) a method that creates an array of parameter from a record object and then call the AddRange function. It should keeps this function cleaner and you could use it also in other part of you code.
In regards to the error, it's a truncation problem i.e. the length of your parameter is longer than what your column can hold. To resolve this, be more specific when passing your parameters e.g. new SqlParameter("#MyParameter", SqlDbType.VarChar, 30).
Personally I don't think their is anything wrong with how your currently adding the parameters it's readable and does the job. If, however, you want to reduce the amont of lines of code in your function you could either go with what #Royi has suggested or simply package up the parameter adding into another method.
This worked for me:
comando.Parameters.Add(
"#EmailAddress", SqlDbType.VarChar).Value = EmailAddress;

How to use c# and datasets to read/write DateTime to SQL Server

I have a table in SQL Server that has a column named sql_DateTime of type datetime. I also have a C# structure that maps to a single record from this table; in this structure is a member named m_DateTime of type DateTime.
My problem occurs after I retrieve a record from this table, using a DataSet, and then try to get the sql_DateTime from the Dataset into my m_DateTime variable. I get an InvalidCastException when I try to do it similar to the way I handle other datatypes.
My hope is then to be able to use a DateTimePicker in my GUI to display and set a date and time.
My code is attached for your reference. Thanks for any guidance.
public bool GetExperiment(ref Experiment exp, int ExperimentID, ref string statusMsg)
{
bool ret = true;
statusMsg = "GetExperiment: ";
try
{
// Open the connection
conn.Open();
// init SqlDataAdapter with select command and connection
string SelectString =
#"SELECT * " +
"FROM Experiment " +
"WHERE ExperimentID = " + ExperimentID.ToString();
SqlDataAdapter daExperiments = new SqlDataAdapter(SelectString, conn);
// fill the dataset
DataSet dsExperiments = new DataSet();
daExperiments.Fill(dsExperiments, "Experiment");
// assign dataset values to proj object that was passed in
exp.m_ExperimentID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ExperimentID"];
exp.m_ProjectID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ProjectID"];
exp.m_Name = (string)dsExperiments.Tables["Experiment"].Rows[0]["Name"];
exp.m_Description = (string)dsExperiments.Tables["Experiment"].Rows[0]["Description"];
exp.m_UserID = (int)dsExperiments.Tables["Experiment"].Rows[0]["UserID"];
// PROBLEM OCCURS HERE
exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"].Rows[0]["DateTime"];
}
catch (Exception ex)
{
ret = false;
statusMsg += "Failed - " + ex.Message;
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
return ret;
}
public class Experiment
{
public int m_ExperimentID;
public int m_ProjectID;
public string m_Name;
public string m_Description;
public int m_UserID;
public DateTime m_DateTime;
}
You say:
I have a table in SQL Server that has a column named sql_DateTime
And yet you use:
exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"]
.Rows[0]["DateTime"];
Note the name. I'm surprised that you're getting a casting problem though. Is it possible that in reality you've got the name right but your row doesn't contain a value, so you're trying to cast DBNull.Value to DateTime?
Additionally, I'd say:
There's no need to pass exp by reference
I would personally separate the exception handling from the database access; I'd let the UI handle the exception
I'd use a named parameter instead of including the experiment ID directly into the SQL
Are you using data binding? If so, are you binding to the proper property? And is the SQL one a nullable type or not?
Try this :
exp.m_DateTime = DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString());
The problem might be that the DataTable containing the data (Tables["Experiment"]) does not think the column ["DateTime"] is of type DateTime but rather a string.
I think you have to alternatives:
If you are sure it's always a DateTime, simply parse it:
exp.m_DateTime =DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString());
Set dsExperiments.Tables["Experiment"].Columns["DateTime"].DataType=typeof(DateTime); before you attempt to read it.

Categories

Resources