My question is quite long because it consist of a lot of code and unfortunately there is no way for me to post it shorter. I have never received such an error before, that is why I'm referring here for help. Your help and time will be highly appreciated!
I'm receiving an error "System.InvalidCastException: Object must implement IConvertible.".
Here is also the error message:
"Line 28: connection.Open();
Line 29: command.Connection = connection;
Line 30: return new SqlResult(connection, command.ExecuteReader());
Line 31: }
Line 32: catch (SqlException se)"
I'm using class I've created called DatabaseHelper. I have inserted comments around Line 30 in the code of the class below (where the error occurs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
public class DatabaseHelper
{
private static String s_lastError;
private static SqlConnection ConnectDB()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
return connection;
}
public static SqlResult ExecuteQueryWithResult(SqlCommand command)
{
SqlConnection connection = ConnectDB();
try
{
connection.Open();
command.Connection = connection;
//------error occurs here Line 30-----//
return new SqlResult(connection, command.ExecuteReader());
//--error occurs here Line 30-----//
}
catch (SqlException se)
{
s_lastError = se.Message;
return null;
}
}
public static void ExecuteQueryNoResult(SqlCommand command)
{
SqlConnection connection = ConnectDB();
try
{
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
}
catch (SqlException se)
{
s_lastError = se.Message;
}
}
public static void AddParameter(SqlCommand command, String paramName, SqlDbType paramType, Object value)
{
SqlParameter parameter = new SqlParameter(paramName, paramType);
parameter.Value = value;
command.Parameters.Add(parameter);
}
public static String GetLastError()
{
return s_lastError;
}
public class SqlResult
{
private SqlDataReader m_reader;
private SqlConnection m_connection;
public SqlResult(SqlConnection connection, SqlDataReader reader)
{
m_connection = connection;
m_reader = reader;
}
public bool HasResults()
{
return m_reader.HasRows;
}
public SqlDataReader GetReader()
{
return m_reader;
}
public Dictionary<string, object> GetNextRow()
{
if (m_reader != null && m_reader.Read())
{
Dictionary<string, object> result = new Dictionary<string, object>();
for (int i = 0; i < m_reader.FieldCount; i++)
{
result.Add(m_reader.GetName(i), m_reader.GetValue(i));
}
return result;
}
return null;
}
public void Close()
{
m_reader.Close();
m_connection.Close();
}
}
}
On the other hand in the Stack trace it is saying:
"[InvalidCastException: Failed to convert parameter value from a Guid to a String.]"
DatabaseHelper.ExecuteQueryWithResult(SqlCommand command) in FOLDERLOCATION\App_Code\DatabaseHelper.cs:30
create_event.createEvent_Click(Object sender, EventArgs e) in FOLDERLOCATION\create_event.aspx.cs:58
Here is the code I've written in create_event.aspx.cs, I've inserted comments arround Line 58 again (where the error occurs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
using System.Collections;
using System.Data;
public partial class create_event : System.Web.UI.Page
{
private int UserID = -1;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
Page.Visible = true;
UserID = Convert.ToInt32(Session["userid"]);
}
else
{
Response.Write("<script language='javascript'>window.alert('To create an event please Login!');window.location='Login.aspx';</script>");
}
}
String newGUID = Guid.NewGuid().ToString();
protected void createEvent_Click(object sender, EventArgs e)
{
if (TextBox_eventName.Text.Length > 0 && TextBox_eventLocation.Text.Length > 0)
{
Guid newGUID = Guid.NewGuid();
int eventID = -1;
SqlCommand addEvent = new SqlCommand("spAddEvent");
addEvent.CommandType = CommandType.StoredProcedure;
addEvent.CommandText = "spAddEvent";
DatabaseHelper.AddParameter(addEvent, "@event_guid", SqlDbType.VarChar, newGUID);
DatabaseHelper.AddParameter(addEvent, "@event_name", SqlDbType.VarChar, TextBox_eventName.Text);
DatabaseHelper.AddParameter(addEvent, "@event_location", SqlDbType.VarChar, TextBox_eventLocation.Text);
DatabaseHelper.AddParameter(addEvent, "@event_description", SqlDbType.Text, TextBox_Description.Text);
DatabaseHelper.AddParameter(addEvent, "@start_time", SqlDbType.DateTime, TextBox_eventSTime.Text);
DatabaseHelper.AddParameter(addEvent, "@end_time", SqlDbType.DateTime, TextBox_eventETime.Text);
DatabaseHelper.AddParameter(addEvent, "@event_type", SqlDbType.VarChar, DropDownListEventType.Text);
DatabaseHelper.AddParameter(addEvent, "@organizer", SqlDbType.Int, UserID);
//------------Line 58 error occurs here--------//
DatabaseHelper.SqlResult added = DatabaseHelper.ExecuteQueryWithResult(addEvent);
//------------Line 58 error occurs here---------//
if (added.HasResults())
{
Dictionary<string, object> eventInfo = added.GetNextRow();
eventID = Convert.ToInt32(eventInfo[""]);
int user_id = -1;
SqlCommand checkUser = new SqlCommand("SELECT user_id FROM Users WHERE email = @email");
DatabaseHelper.AddParameter(checkUser, "@email", SqlDbType.VarChar, TextBox_inviteGuest.Text);
DatabaseHelper.SqlResult userResult = DatabaseHelper.ExecuteQueryWithResult(checkUser);
if (!userResult.HasResults())
{
userResult.Close();
SqlCommand AddUser = new SqlCommand("spAddUsers");
AddUser.CommandType = CommandType.StoredProcedure;
AddUser.CommandText = "spAddUsers";
DatabaseHelper.AddParameter(AddUser, "@email", SqlDbType.VarChar, TextBox_inviteGuest.Text);
DatabaseHelper.SqlResult insertS = DatabaseHelper.ExecuteQueryWithResult(AddUser);
if (insertS.HasResults())
{
user_id = Convert.ToInt32(insertS.GetNextRow()[""]);
}
}
else
{
Dictionary<string, object> result = userResult.GetNextRow();
user_id = Convert.ToInt32(result["user_id"]);
}
userResult.Close();
SqlCommand checkUserEvent = new SqlCommand("spCheckUserEvent");
checkUserEvent.CommandType = CommandType.StoredProcedure;
checkUserEvent.CommandText = "spCheckUserEvent";
DatabaseHelper.AddParameter(checkUserEvent, "@user_id", SqlDbType.Int, user_id);
DatabaseHelper.AddParameter(checkUserEvent, "@event_id", SqlDbType.Int, eventID);
DatabaseHelper.AddParameter(checkUserEvent, "@role", SqlDbType.VarChar, Status.guest);
DatabaseHelper.AddParameter(checkUserEvent, "@status", SqlDbType.VarChar, Status.awaitingAnswer);
DatabaseHelper.ExecuteQueryNoResult(checkUserEvent);
{
const string username = "XXXX";
const string password = "XXXX";
SmtpClient smtpclient = new SmtpClient();
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
MailAddress fromaddress = new MailAddress("XXXX");
smtpclient.Host = "smtp.gmail.com";
smtpclient.Port = 587;
mail.From = fromaddress;
mail.To.Add(TextBox_inviteGuest.Text);
mail.Subject = ("Invitation for an event: " + TextBox_eventName.Text);
mail.IsBodyHtml = true;
string eventLink = "http://localhost:61638/NewEvent.aspx?" + "Guid=" + newGUID + "&" + "email=" + TextBox_inviteGuest.Text;
string eLink = "<a href=\"" + eventLink + "\">" + eventLink + "</a>";
mail.Body = "Hello," + "<br /><br />" +
"You have been invited to <b>'" + TextBox_eventName.Text + "'</b><br /><br />" +
"Please click the link below to let the organizer know if you can make it, see the details and leave a comment. <br />" + eLink + "<br /><br />" +
"Best regards, " + "<br />" + "The team of XXX.";
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
try
{
smtpclient.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Response.Redirect("NewEvent.aspx?guid=" + newGUID);
}
else
{
LabelError.Text = "You haven't inserted Event name and Event location!";
}
}
}
Please excuse me for the long question and thanks to everyone who has couple minutes to spare helping me resolve my issue.
The error seems to be simple. You added the parameter event_guid
which is declared to be a varchar but your c# parameter newGUID
is a GUID
and not a string. Use newGUID.ToString()
instead, but you have to be carfeful about the formatting. If you want to store the GUID without -
in between please refer to https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx
DatabaseHelper.AddParameter(addEvent, "@event_guid", SqlDbType.VarChar, newGUID.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With