Basically if a parameter comes in as NULL, I want to send it to the database as a database NULL. As such (look at the comment inside the code below):
[HttpPost]
public void UpdateTitle(Title title)
{
string query = null;
string description = "";
string episodeAKA = "";
if (title.Description != null)
{
description = "'" + title.Description + "'";
}
else
{
//here's where description should be a DBNULL.
}
if (title.EpisodeAKA == null)
{
title.EpisodeAKA = "NULL";
}
myConnection.Open();
if (title.Operation == 'U')
{
query = "UPDATE dbo.AWD_Titles SET AwardStatusId = " + title.AwardStatus + ", Description = " + description + ", IsVerified = " + title.IsVerified + ", EpisodeAKA = '" + title.EpisodeAKA + "' WHERE AwardTitleId = " + title.AwardTitleId + " SELECT SCOPE_IDENTITY()";
}
var cmd = new SqlCommand(query, myConnection);
cmd.ExecuteScalar();
myConnection.Close();
}
}
And here's the class for Title:
public class Title
{
public int AwardTitleId
{
get;
set;
}
public int AwardStatus
{
get;
set;
}
public int IsVerified
{
get;
set;
}
public string EpisodeAKA
{
get;
set;
}
public string Description
{
get;
set;
}
public char Operation
{
get;
set;
}
}
The original code had several fundamental errors. This demonstrates how to do it right, including how to set DBNull:
[HttpPost]
public void UpdateTitle(Title title)
{
string query;
if (title.Operation == 'U')
{
query =
"UPDATE dbo.AWD_Titles" +
" SET AwardStatusId = #AwardStatusID , Description = #Description , IsVerified= #IsVerified , EpisodeAKA= #EpisodeAKA" +
" WHERE AwardTitleId= #AwardTitleId ;" +
" SELECT SCOPE_IDENTITY();";
} else {
query="";
//presumably you have a slightly different query string for inserts.
//Thankfully, they should have pretty much the same set of parameters.
//If this method will really only be called for updates, the code is quite a bit simpler
}
//instead of a shared myConnection object, use a shared connection string.
// .Net is set up so that you should be creating a new connection object for most queries.
// I know it sounds backwards, but that's really the right way to do it.
// Create the connection in a using(){} block, so that you guarantee it is
// disposed correctly, even if an exception is thrown.
using (var cn = new SqlConnection(myConnectionString))
using (var cmd = new SqlCommand(query, cn))
{
//guessing at database types, lengths here. Fix with actual column types
cmd.Parameters.Add("#AwardStatusId", SqlDbType.Int).Value = title.AwardStatus;
cmd.Parameters.Add("#Description", SqlDbType.NVarChar, 250).Value = title.Description;
cmd.Parameters.Add("#IsVerified", SqlDbType.Bit).Value = title.IsVerified;
cmd.Parameters.Add("#EpisodeAKA", SqlDbType.NVarChar, 100).Value = title.EpisodeAKA;
cmd.Parameters.Add("#AwardTitleId", SqlDbType.Int).Value = title.AwardTitleId;
//-------------
//This is the part that actually answers your question
foreach (var p in cmd.Parameters.Where(p => p.Value == null))
{
p.Value = DBNull.Value;
}
//-------------
cn.Open();
cmd.ExecuteScalar();
}
}
Well, with the code that you have, you could just use null in the SQL code:
description = "null";
However, you should really use a parameterised query instead of concatenating values into the SQL code. If any of the data comes from user input, your code is wide open to SQL injection attacks.
For a parameter value you use DBNull.Value for a null value, so the variable holding it has to be an object:
object description;
if (title.Description != null) {
description = title.Description;
} else {
description = DBNull.Value;
}
Now you can use that value in an SqlParameter object.
Ok, first things first. Your code is asking for a SQL injection attack. Use parameterized queries.
Unto the question itself. You need to pass the value DBNull.Value if what you want is a data base NULL. You could use a helper function that converts your string to the appropriate value.
private object ConvertToDbReadyString(string value)
{
if(value=="NULL")
return DBNull.Value;
else
return value;
}
if (title.Description != null)
{
description = "'" + title.Description + "'";
}
else
{
//here's where description should be a DBNULL.
}
try this one:
description = title.Description ?? string.Empty;
string variableValue == string.IsNullOrEmpty(stringValue) ? null : "Hello";
Related
I am getting the error as
Input string was not in a correct format.
newRow["col_frm_bin_id"] = CF.ExecuteScaler("Select location_name from wms_storage_bin where mkey = " + e.Record["from_bin"] + "");
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
int val=Convert.ToInt32(cmd.ExecuteScalar());
DB.conn.Close();
string ret = val.ToString();
return ret;
}
I tried with converting but still it didn't worked
Your return column name sounds like its a string variable, Change it with int type column, or remove Convert.ToInt32 from code side
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
string ret=cmd.ExecuteScalar().ToString();
DB.conn.Close();
return ret;
}
i think you should do like this but this is not good practice and also not safe
your mkey value should be in between quotes
mkey = '" + e.Record["from_bin"] + "'
newRow["col_frm_bin_id"] = CF.ExecuteScaler("Select location_name from wms_storage_bin where mkey = '" + e.Record["from_bin"] + "'");
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
int val=Convert.ToInt32(cmd.ExecuteScalar());
DB.conn.Close();
string ret = val.ToString();
return ret;
}
but sending parameters is best practice
I'll try summarize various pieces of information from other answers and comments.
First, your existing code is open to Sql injections. This is a very bad thing. To avoid the risk of Sql injection you shoul use Parametrized queries. See for instance here.
That means your ExecuteScaler method should not take a string as its argument, but instead a SqlCommand (I have corrected the spelling of scalar):
public string ExecuteScalar(SqlCommand query) { ... }
Your current implementation of ExecuteScaler is also at risk of leaking SqlConnetions. If an exception is thrown in this method before the DB.conn.Close() line, the connection will not be closed. For instance, in the case you described in the question, the following line is the prime suspect:
int val = Convert.ToInt32(cmd.ExecuteScalar());
With your current call to the method, you seem to be fetching something that is a string from the database. Unless that string is convertible to Int32, this line will throw an exception, and the connection will not be closed. To fix this, you should at the minimum add a try { ... } finally { ... } block:
public string ExecuteScalar(SqlCommand query)
{
try
{
DB.EConnection();
query.Connection = DB.conn;
string ret = query.ExecuteScalar().ToString();
return ret;
}
finally
{
if(DB.conn.State == ConnectionState.Open)
DB.conn.Close();
}
}
I would also suggest that you create separate versions of ExecuteScalar for different expected return types. Perhaps:
public string GetStringScalar(SqlCommand query)
public int GetInt32Scalar(SqlCommand query)
etc.
The calling code then needs to be changed:
string locName = null;
using (SqlCommand locNameCommand = new SqlCommand(#"
select location_name
from wms_storage_bin
where mkey = #mkey
"))
{
locNameCommand.Parameters.AddWithValue("mkey", e.Record["from_bin"]);
locName = GetStringScalar(locNameCommand);
}
newRow["col_frm_bin_id"] = locName;
An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
I have a SQL-server and a column called CitizenshipDate. That column is of type datetime in the SQL.
However, the problem is that it can have the value '0' which is NOT a datetime value but rather a string value.
So what I'm trying to do is to handle it as a string in C# when inserting it values but get the error:
Conversion failed when converting datetime from character string.
I get that error because I'm trying to insert string into a datetime in the SQL-server.
Here is my code:
class Person {
public string PersonalIdentityNumber { get; set; }
public string SpecialIdentityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CitizenshipDate { get; set; }
}
List<FolkbokforingspostTYPE> deserializedList = new List<FolkbokforingspostTYPE>();
deserializedList = Deserialize<List<FolkbokforingspostTYPE>>();
var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
.Select(x => new Person
{
PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
SpecialIdentityNumber = x.Personpost.PersonId.Tilltalsnamnsmarkering != null ? x.Personpost.PersonId.Tilltalsnamnsmarkering : null,
LastName = x.Personpost.Namn.Efternamn,
FirstName = x.Personpost.Namn.Fornamn,
CitizenshipDate = x.Personpost.Medborgarskap != null ? x.Personpost.Medborgarskap.Medborgarskapsdatum : null
});
string connetionString = null;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile;
connetionString = "Data Source=tsrv2062;Initial Catalog=Bums;User ID=BumsUser;Password=2tusen7Bums";
xmlFile = XmlReader.Create("navetout.xml", new XmlReaderSettings());
ds.ReadXml(xmlFile);
using (var connection = new SqlConnection(connetionString))
{
connection.Open();
DateTime datum = DateTime.Now;
string LastChangedBy = "System";
foreach (Person p in myPersons)
{
SqlCommand command1 = Avreg(p.UnregistrationReason, p.GivenNameNumber,p.ProtectedIdentity, p.CitizenshipDate, connection);
command1.Parameters.AddWithValue("#PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
command1.Parameters.AddWithValue("#FirstName", p.FirstName);
command1.Parameters.AddWithValue("#LastName", p.LastName);
command1.ExecuteNonQuery();
Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
}
}
Console.WriteLine("Done");
// }// Put a break-point here, then mouse-over PersonalIdentityNumber... deserializedList contains everything if you need it
//catch (Exception)
// {
// throw;
// }
Console.ReadKey();
}
public static SqlCommand Avreg(string s, string t, string p, string c, SqlConnection connection)
{
var query = "UPDATE Seamen SET FirstName = #FirstName, "+
"LastName = #LastName, "+
SqlCommand command1;
//Here is the `CitizenshipDate`
if (c == "0")
{
query += ", CitizenshipDate = '0'";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
}
else
{
query += ", CitizenshipDate = #CitizenshipDate";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
command1.Parameters.AddWithValue("#CitizenshipDate", c ?? DBNull.Value.ToString());
}
//Ignore these if statements
if ((!string.IsNullOrEmpty(s)) && !string.IsNullOrEmpty(t))
{
}
else
{
query += ", GivenNameNumber = #GivenNameNumber WHERE PersonalIdentityNumber = #PersonalIdentityNumber";
t = "00";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
command1.Parameters.AddWithValue("#GivenNameNumber", t ?? DBNull.Value.ToString());
return command1;
}
return command1;
}
Please note that I cannot change the type in the database. I somehow need a way to insert the value from String.
Can someone help ?
If the column does not allow nulls, then you can use NULL to represent "0", and then in code, when loading the record, replace NULL with "0" in the UI. Or, if you do allow NULLS and need another value to represent "0", you can use an arbitrary date you wouldn't normally use like '1/1/1753' (the lowest value for SQL datetime) or '1/1/1900' (lowest for smalldatetime) or something like that. Any date that is these dates represents "0". So the conversion to "0" happens within the app, not stored in the database.
If your column supports null you can fix it like this:
if (c == "0")
{
query += ", CitizenshipDate = NULL--instead of '0'";
If it does not support NULL values you will have to insert a default value such as DateTime.MinValue.
I seem to have a weird problem and I can't figure out what I'm doing wrong.
My code should update a record but it won't.
IDbCommand cmd = ((IConnectionProvider) _Tender).Connection.CreateCommand();
if(_ID == null)
{
cmd.CommandText = "INSERT INTO ELEMENTS (ID, HOP, HMODE, HSORT, HFLAGS, KPARENT, TEMPLATE, NUMV, NAMV, TITLE, TXTV, RESERVED, CDATA, VDATA) VALUES (#id, #hop, #hmode, #hsort, #hflags, #kparent, #template, #numv, #namv, #title, #txtv, #reserved, #cdata, #vdata)";
_ID = _CreateID();
_Tender.Factory._Cache.Add(_ID, this);
}
else
{
cmd.CommandText = "UPDATE ELEMENTS SET HOP = #hop, HMODE = #hmode, HSORT = #hsort, HFLAGS = #hflags, KPARENT = #kparent, TEMPLATE = #template, NUMV = #numv, NAMV = #namv, TITLE = #title, TXTV = #txtv, RESERVED = #reserved, CDATA = #cdata, VDATA = #vdata WHERE ID = #id";
}
cmd.AddParameter("#id", _ID);
cmd.AddParameter("#hop", _ActualType);
cmd.AddParameter("#hmode", _Mode);
cmd.AddParameter("#hsort", _Sort);
cmd.AddParameter("#hflags", _Flags);
cmd.AddParameter("#kparent", ((_Parent == null) ? "" : _Parent.ID));
cmd.AddParameter("#template", ((_Template == null) ? "" : _Template.ToString()));
cmd.AddParameter("#numv", _Number);
cmd.AddParameter("#namv", _Name);
cmd.AddParameter("#title", _Title);
cmd.AddParameter("#txtv", _Text);
cmd.AddParameter("#reserved", _Reserved);
cmd.AddParameter("#cdata", _CData);
cmd.AddParameter("#vdata", _VData);
int v = cmd.ExecuteNonQuery();
The INSERT part works just fine. The UPDATE part doesn't update the record for reasons I can't understand. v in the last statement is 0.
If I put the command text like that:
cmd.CommandText = "UPDATE ELEMENTS SET HOP = #hop, HMODE = #hmode, HSORT = #hsort, HFLAGS = #hflags, KPARENT = #kparent, TEMPLATE = #template, NUMV = #numv, NAMV = #namv, TITLE = #title, TXTV = #txtv, RESERVED = #reserved, CDATA = #cdata, VDATA = #vdata WHERE ID = '" + _ID + "'";
(not using a bind variable in the WHERE clause) it works (v == 1).
I'm using the interfaces for portability reasons, I wrote AddParameter() extension methods for convenience.
_ID is an alphanumeric value like "g5fRRa3P89gX" or something.
_Connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";");
public static IDbDataParameter AddParameter(this IDbCommand cmd, string name, DbType type, object value)
{
IDbDataParameter p = cmd.CreateParameter();
p.DbType = type;
p.ParameterName = name;
p.Value = value;
if(value is string)
{
p.Size = ((string) value).Length;
if(p.Size == 0) { p.Size = 1; }
}
else
{
p.Size = sizeof(int);
}
cmd.Parameters.Add(p);
return p;
}
public static IDbDataParameter AddParameter(this IDbCommand cmd, string name, string value)
{
return AddParameter(cmd, name, DbType.String, value);
}
public static IDbDataParameter AddParameter(this IDbCommand cmd, string name, int value)
{
return AddParameter(cmd, name, DbType.Int32, value);
}
Does anyone have an idea about that?
Thanks, Alex.
I have found the solution and it is less awkward as I had thought. It seems the driver simply doesn't support named parameters. This is somehow strange because you can define and use them, but apparently they will always be applied in the order they were added to the command disregarding their names.
Thus, the code will work for the UPDATE part when #id parameter is assigned last...
I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.
What I might try right now would be:
ISessionFactoryHolder factoryHolder = ActiveRecordMediator<EntityClass>.GetSessionFactoryHolder();
ISession session = factoryHolder.CreateSession(typeof(EntityClass));
try
{
IDbCommand cmd = session.Connection.CreateCommand();
cmd.CommandText = "spName";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
finally
{
factoryHolder.ReleaseSession(session);
}
However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.
This works for me (stored procedure with params and dynamic result table):
// get Connection
System.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder()
.GetSessionFactory(typeof(Autocomplete))
.ConnectionProvider.GetConnection();
// set Command
System.Data.IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "name_of_stored_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// set Parameter of Stored Procedure
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("#parameter_name", System.Data.SqlDbType.NVarChar);
param.Value = "value_of_parameter";
((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param);
// call Stored Procedure (without getting result)
cmd.ExecuteNonQuery();
// ... or read results
System.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader();
while(r.Read()) {
System.Console.WriteLine("result first col: " + r.GetString(0));
}
The blog I used when implementing stored procedures in my ActiveRecord code was this post by Rodj (http://blog.rodj.org/archive/2008/05/23/activerecord-nhibernate-and-sql-stored-procedures.aspx). Using his post and the comments I was able to get this to work. I haven't decided if this is the best way yet.
You can also get an IDbConnection with:
ActiveRecordMediator.GetSessionFactoryHolder()
.GetSessionFactory(typeof(ActiveRecordBase))
.ConnectionProvider.GetConnection();
For ActiveRecord version 1, this works:
IDbConnection connection = ActiveRecordMediator.GetSessionFactoryHolder()
.GetSessionFactory(typeof(ActiveRecordBase))
.OpenSession().Connection;
public ArrayList DevolverCamposDeObjetoSTP(T Objeto, List<Consulta> Consultas, string StoredProcedureName)
{
ArrayList results;
try
{
var queryString = #"EXEC " + StoredProcedureName;
foreach (var consulta in Consultas)
{
switch (consulta.tipoCampo)
{
case Consulta.TipoCampo.dato:
queryString = queryString + " " + consulta.Campo + " = " + "'" + consulta.Valor + "'";
break;
case Consulta.TipoCampo.numero:
queryString = queryString + " " + consulta.Campo + " = " + consulta.Valor;
break;
}
queryString = queryString + ",";
}
queryString = queryString.Remove(queryString.Count() - 1, 1);
var query = new HqlBasedQuery(typeof(T),QueryLanguage.Sql, queryString);
results = (ArrayList)ActiveRecordMediator.ExecuteQuery(query);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
return results;
}
public class Consulta
{
public enum TipoCampo
{
dato,
numero
}
public string Campo { get; set; }
public TipoCampo tipoCampo { get; set; }
public string Valor { get; set; }
public string Indicador { get; set; }
}
public void _Pruebastp()
{
var p = new Recurso().DevolverCamposDeObjetoSTP(
new Recurso(),
new List<Consulta> { new Consulta { Campo = "#nombre", tipoCampo = Consulta.TipoCampo.dato, Valor = "chr" }, new Consulta { Campo = "#perfil", tipoCampo = Consulta.TipoCampo.numero, Valor = "1" } },
"Ejemplo");
}