When i try to execute this function i get the error "System.InvalidCastException: Specified cast is not valid."
System.InvalidCastException: Specified cast is not valid.
at server.mihail.credits.HandleRequest() in F:\Users\Mihail\Documents\new-sentients-2016\server\mihail\credits.cs:line 34
at server.RequestHandler.HandleRequest(HttpListenerContext context) in F:\Users\Mihail\Documents\new-sentients-2016\server\RequestHandlers.cs:line 37
at server.Program.ProcessRequest(HttpListenerContext context) in F:\Users\Mihail\Documents\new-sentients-2016\server\Program.cs:line 156
This is the function: I try to execute it with parameters guid as my email address and parameter aid with the number one in it.
Please help me, i have been trying all day to fix it.
class credits : RequestHandler
{
protected override void HandleRequest()
{
string status = "403";
using (Database db = new Database())
{
NameValueCollection query = HttpUtility.ParseQueryString(Context.Request.Url.Query);
MySqlCommand cmd = db.CreateQuery();
cmd.CommandText = "SELECT id FROM accounts WHERE uuid=@uuid";
cmd.Parameters.AddWithValue("@uuid", query["guid"]);
object id = cmd.ExecuteScalar();
if (id != null)
{
int amount = int.Parse(query["aid"]);
cmd = db.CreateQuery();
cmd.CommandText = "UPDATE stats SET credits = credits + @amount WHERE accId=@accId";
cmd.Parameters.AddWithValue("@accId", (int) id);
cmd.Parameters.AddWithValue("@amount", amount);
int result = cmd.ExecuteNonQuery();
if (result > 0)
status = "400";
else
status = "500";
}
else
status = "404";
}
byte[] res = Encoding.UTF8.GetBytes(
status);
Context.Response.OutputStream.Write(res, 0, res.Length);
}
}
Based on the limited information you have provided, it looks like the problem is with the line cmd.Parameters.AddWithValue("@accId", (int) id);
, as that is the only line with a cast.
Check the type of the accounts.id
column in your database, I suspect it is not an INT
, so you will need to change the cast (the type in the parentheses) to whatever type it is. A SMALLINT
is a short
in C#, BIGINT
is long
, TINYINT
is byte
(or sbyte
), and you'd need to look at the documentation to see what MEDIUMINT
maps to, but its probably int
.