RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string - type-conversion

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.

Related

ADO.NET add SQLParameters

I am trying to execute a stored procedure with parameters using ADO.NET in .NET Core.
When I try and pass in a SqlParameter object I get the below error.
I have a using statement at the top for System.Data.SqlClient.
Is there another way or new ways of passing Sql parameters to a stored procedure?
public async Task<List<SynchStockDto>> GetStockForSync(int locationBinId, DateTime lastSyncDate)
{
await EnsureConnectionOpenAsync();
var command = GetConnection().CreateCommand();
command.CommandText = "sp_GetStockForSync #LocationBinId, #LastSyncDate";
command.CommandType = CommandType.StoredProcedure;
command.Transaction = GetActiveTransaction();
command.Parameters.Add(new SqlParameter("LocationBinId",locationBinId)); //not finding SQLParameter method
using (var dataReader = await command.ExecuteReaderAsync())
{
var result = new List<SynchStockDto>();
while (dataReader.Read())
{
var stockItem = new SynchStockDto
{
};
result.Add(stockItem);
}
return result;
}
}

ORA-06550 , wrong number or types of arguments in call to Oracle Stored Procedure

I have a stored procedure which has one in parameter and one out parameter as follows:
create or replace procedure worker_name (w_id in number, w_first out worker.first_name%type) is
Begin
select first_name into w_first
from worker
where worker_id = w_id;
end;
Code to call this stored procedure:
public DataTable <b>GetEmployeeName</b>(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter(":employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.<b>GetData</b>("macw_conv.worker_name", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}
public DataTable <b>GetData</b>(string query, ArrayList parameters,string queryType)
{
//DataTable dt = new DataTable();
try
{
_con =
new OracleConnection(Oradb);
_con.Open();
_cmd = new OracleCommand(query, _con);
if (_cmd.Connection.State == ConnectionState.Open)
{
if (queryType == "SP" && parameters != null)
{
_cmd.CommandType = CommandType.StoredProcedure;
if (parameters.Count > 0)
{
foreach (OracleParameter param in parameters)
{
_cmd.Parameters.Add(param);
}
}
}
}
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(_cmd);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
return ds.Tables[0];
}
return null;
}
I guess I'm unable to see the obvious error. It's something about the data type mismatch between the out parameter in the stored procedure and output parameter in the code. Any kind of help is appreciated.
Thanks!
I figured out the issue: it was because the datatype of the variable that is saving the out parameter was not handled properly. I changed the code as follows:
try
{
_con = new OracleConnection(Oradb);
_cmd = _con.CreateCommand();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandText = "macw_conv.worker_name";
OracleParameter inobj1 = _cmd.Parameters.Add("w_id", OracleDbType.Int32,50);
inobj1.Direction = ParameterDirection.Input;
inobj1.Value = _employeeID;
OracleParameter inobj2 = _cmd.Parameters.Add("w_last", OracleDbType.Int32, 50);
inobj2.Direction = ParameterDirection.Input;
inobj2.Value = String.IsNullOrEmpty(_lastName) ? null : _lastName;
OracleParameter outobj = _cmd.Parameters.Add("w_first", OracleDbType.Varchar2, 50);
outobj.Direction = ParameterDirection.Output;
_con.Open();
_cmd.ExecuteNonQuery();
_employeeName = ((OracleString) _cmd.Parameters[1].Value).ToString();
_cmd.Dispose();
_con.Close();
}
catch (OracleException ex)
{
Console.WriteLine(ex.Message);
}
return _employeeName;
Try
public DataTable GetEmployeeName(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter("employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
OracleParameter paramEmployeeFirst = new OracleParameter("first", OracleDbType.Varchar2, ParameterDirection.Output);
arrEmployeeName.Add(paramEmployeeFirst);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.GetData("macw_conv.worker_name(:1,:2)", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}

expects parameter which was not supplied

I would want to know whats the reason for the following error. If you can help, I would greatly appreciate it.
The error is:
Procedure or function 'Sp_Informacion_gral_Cliente' expects parameter '#Cod_Medico', which was not supplied.
The URL I put in the browser:
http://localhost:2731/Api/Usuario/0000986
The MapRoute in the ApiAreaRegistration:
context.MapRoute(
"DetailClientes",
"Api/Usuario/{Detail}",
new
{
controller = "Usuario",
action = "Detail"
}
);
The Controller method:
[HttpGet]
public JsonResult Detail(string codigo)
{
return Json(clientesManager.ObtenerClienteDetallado(codigo),
JsonRequestBehavior.AllowGet);
}
And the method where maybe the error occur:
public List<ClienteDetallado> ObtenerClienteDetallado(string cliente)
{
List<ClienteDetallado> lista = new List<ClienteDetallado>();
SqlConnection con = new SqlConnection(cadenaConexionVM);
con.Open();
SqlCommand cmd = new SqlCommand("Sp_Informacion_gral_Cliente", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Cod_Medico", SqlDbType.NChar).Value = cliente;
SqlDataReader reader =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (reader.Read())
{
ClienteDetallado cli = new ClienteDetallado();
cli = new ClienteDetallado();
cli.Cod_Medico = reader.GetInt32(0);
cli.Nombre = reader.GetString(1);
cli.Apellido = reader.GetString(3);
cli.Fecha_Nacimiento = reader.GetString(4);
cli.Lugar_Nacimiento= reader.GetString(5);
cli.celular= reader.GetString(6);
cli.tel_ofic= reader.GetString(7);
cli.Estilo_De_Conducta = reader.GetString(8);
cli.pasatiempos= reader.GetString(9);
cli.Membresías_Grupos_Asc= reader.GetString(10);
cli.Especialidad= reader.GetString(11);
cli.Facultad_Medicina= reader.GetString(12);
cli.Lugar_Donde_Obtuvo_Especialidad= reader.GetString(13);
cli.Tiempo_Ejerciendo_Especialidad= reader.GetString(14);
cli.Lugar_Donde_Labora = reader.GetString(15);
cli.Direccion_CS_Labora= reader.GetString(16);
cli.Direccion_Consultorio = reader.GetString(17);
cli.Horario_Labor= reader.GetString(18);
cli.Lugar_prefiere_recibir_Visitadores_Médicos= reader.GetString(19);
cli.Productos_que_Receta_actualmente= reader.GetString(20);
cli.Potencial_de_receta_actual= reader.GetString(21);
cli.Costo_Promedio_Consulta= reader.GetString(22);
lista.Add(cli);
}
reader.Close();
return lista;
}
Try matching the expected data name to match your controller. So your route would look like the following.
context.MapRoute(
"DetailClientes",
"Api/Usuario/{codigo}",
new
{
controller = "Usuario",
action = "Detail"
}
);
Your stored procedure is not getting a value from 'string cliente' that it expects to be present.

Submitting a WebRequest from within a CLR Trigger

I just implemented a prototype solution for updating my caching server in real-time by assigning a CLR Trigger to a table so that whenever a certain column is updated the URL called from the trigger will update the caching server with the correct data.
It's working fine and the code is as follows:
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AdStatusChanged", Target = "Ads", Event = "FOR UPDATE")]
public static void AdStatusChanged()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
int adID = 0, adStatusID_Old = 0, adStatusID_New = 0;
if (triggContext.TriggerAction == TriggerAction.Update)
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand();
SqlPipe sqlP = SqlContext.Pipe;
sqlComm.Connection = conn;
sqlComm.CommandText = "SELECT AdID, AdStatusID from INSERTED";
SqlDataReader reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_New = reader.GetInt32(1);
}
reader.Close();
sqlComm.CommandText = "SELECT AdID, AdStatusID from DELETED WHERE AdID = " + adID;
reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_Old = reader.GetInt32(1);
}
}
if (adID == 0 || adStatusID_New == adStatusID_Old)
{
// Check could be more thorough !
return;
}
WebResponse httpResponse = null;
try
{
string apiURL = string.Format("{0}/{1}", "http://localhost:14003/Home", "UpdateAdStatus?adID=" + adID + "&adStatusID=" + adStatusID_New);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
httpWebRequest.Method = "GET";
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// check for successful response
}
catch (Exception ex)
{
Log("WebRequest from within SQL Server failed ! " + ex.Message);
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
I would like to have some expert/experienced views on the "CONS" of this approach regarding performance, deadlocks, sql crashing, or other areas that could be of potential concern.
Has anyone tried this (I'm sure many must have) and what was the result ? a successful implementation or did you revert to some other method or updating the cache real-time?

build index using lucene.net 2.9.2.2

I have to use lucene.net 2.9.2.2 with NHibernate 3.0. I have started to edit this old code:
public void BuildSearchIndex()
{
FSDirectory entityDirectory = null;
IndexWriter writer = null;
var entityType = typeof(MappedSequence);
var indexDirectory = new DirectoryInfo(GetIndexDirectory());
if (indexDirectory.Exists)
{
indexDirectory.Delete(true);
}
try
{
entityDirectory = FSDirectory.GetDirectory(Path.Combine(indexDirectory.FullName, entityType.Name), true);
writer = new IndexWriter(entityDirectory, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29), true, IndexWriter.MaxFieldLength.UNLIMITED);
}
finally
{
if (entityDirectory != null)
{
entityDirectory.Close();
}
if (writer != null)
{
writer.Close();
}
}
IFullTextSession fullTextSession = Search.CreateFullTextSession(this.Session);
// Iterate through Suppliers and add them to Lucene's index
foreach (MappedSequence instance in Session.CreateCriteria(typeof(MappedSequence)).List<MappedSequence>())
{
fullTextSession.Index(instance);
}
}
private string GetIndexDirectory()
{
INHSConfigCollection nhsConfigCollection = CfgHelper.LoadConfiguration();
string property = nhsConfigCollection.DefaultConfiguration.Properties["hibernate.search.default.indexBase"];
var fi = new FileInfo(property);
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fi.Name);
}
to build the index. The line:
FSDirectory.GetDirectory(Path.Combine(indexDirectory.FullName, entityType.Name), true);
still uses obsolete code. Could anyone be so kind and point out the necessary change. Thanks.
Christian
PS
Try using FSDirectory.Open(path) instead.