How can return this from method ????
this is important for me
thank
this is my method :
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
return result ;
}
else
{
return ProperiesObject();
}
}
}
and this is my ExpandoObject()
public static dynamic ProperiesObject()
{
dynamic obj = new ExpandoObject();
obj.FactorDate = string.Empty;
obj.FactorNumber = string.Empty;
obj.CustomerName = string.Empty;
obj.FactorPrice = string.Empty;
obj.Discount = string.Empty;
return obj;
}
and this is read from method source :
var result = Program.GetFactorProperties(factornumber);
TXTDate.Text = result.FactorDate;
TXTFactorNumber.Text = result.FactorNumber;
TXTCustomerName.Text = result.CustomerName;
TXTFactorParice.Text = result.FactorPrice;
TXTDiscount.Text = result.Discount;
Method should look like this:
public static dynamic GetFactorProperties(int factornumber)
{
using (var db = new OleDbConnection(cs))
{
db.Open();
var cmd = new OleDbCommand("SELECT * FROM FactorList WHERE FactorNumber = #0", db);
cmd.Parameters.AddWithValue("#0", factornumber);
var result = cmd.ExecuteReader();
if(result.Read())
{
dynamic obj = new ExpandoObject();
obj.FactorDate = result.GetString(0);
obj.FactorNumber = result.GetString(1);
// ...
return obj;
}
else
{
return ProperiesObject();
}
}
}
GetString accepts number of column, from which you want to get value
Code below is me trying to do just that. It returns all rows but only like DEFAULT VALUES (0, empty string, empty date...) and "Allow Nulls" is false for all columns in my db table. I am truly stuck. I am still in process of learning c#, so if someone could please explain to me WHAT am I doing wrong here? Is there a better way to do this?
public List<XNarudzbe> GetXNarudzbe()
{
var listXnar = new List<XNarudzbe>();
using (SqlConnection NConnection = new SqlConnection(Params.ConnectionStr))
{
NConnection.Open();
using (var cmd = new SqlCommand("SELECT * FROM [dbo].[XDATA_NARUDZBE]", NConnection))
{
SqlDataReader reader = cmd.ExecuteReader();
int id = reader.GetOrdinal("ID");
int dt_get = reader.GetOrdinal("DT_GET");
int rn_datum = reader.GetOrdinal("RN_DATUM");
int datum = reader.GetOrdinal("DATUM");
int dt_stamp = reader.GetOrdinal("DT_STAMP");
int art_id = reader.GetOrdinal("ART_ID");
int cijena_k = reader.GetOrdinal("CIJENA_K");
int cijena_mp = reader.GetOrdinal("CIJENA_MP");
int cijena_vp = reader.GetOrdinal("CIJENA_VP");
int faktura = reader.GetOrdinal("FAKTURA");
int isporuceno = reader.GetOrdinal("ISPORUCENO");
int iznos_k = reader.GetOrdinal("IZNOS_K");
int iznos_p = reader.GetOrdinal("IZNOS_P");
int naruceno = reader.GetOrdinal("NARUCENO");
int narudzba = reader.GetOrdinal("NARUDZBA");
int otpremnica = reader.GetOrdinal("OTPREMNICA");
int pdv = reader.GetOrdinal("PDV");
int povrat_k = reader.GetOrdinal("POVRAT_K");
int povrat_p = reader.GetOrdinal("POVRAT_P");
int pp_id = reader.GetOrdinal("PP_ID");
int preporuka = reader.GetOrdinal("PREPORUKA");
int rabat = reader.GetOrdinal("RABAT");
int rn_id = reader.GetOrdinal("RN_ID");
int skart = reader.GetOrdinal("SKART");
int user_id = reader.GetOrdinal("USER_ID");
int var_n = reader.GetOrdinal("VAR_N");
int var_v = reader.GetOrdinal("VAR_V");
int veleprodaja = reader.GetOrdinal("VELEPRODAJA");
int vraceno = reader.GetOrdinal("VRACENO");
int isporuka_id = reader.GetOrdinal("ISPORUKA_ID");
int otpremljeno = reader.GetOrdinal("OTPREMLJENO");
int promjena = reader.GetOrdinal("PROMJENA");
int rj_id = reader.GetOrdinal("RJ_ID");
int zakljucano = reader.GetOrdinal("ZAKLJUCANO");
if (reader.HasRows)
{
while (reader.Read())
{
var recXNar = new XNarudzbe();
recXNar.id = reader["ID"] as decimal? ?? 0M; // reader.GetDecimal(id);
recXNar.dt_get = reader.GetDateTime(dt_get);
recXNar.rn_datum = reader.GetDateTime(rn_datum);
recXNar.datum = reader.GetDateTime(datum);
recXNar.dt_stamp = reader.GetDateTime(dt_stamp);
recXNar.art_id = reader.GetDecimal(art_id);
recXNar.cijena_k = reader.GetDecimal(cijena_k);
recXNar.cijena_mp = reader.GetDecimal(cijena_mp);
recXNar.cijena_vp = reader.GetDecimal(cijena_vp);
recXNar.faktura = reader.GetDecimal(faktura);
recXNar.isporuceno = reader.GetDecimal(isporuceno);
recXNar.iznos_k = reader.GetDecimal(iznos_k);
recXNar.iznos_p = reader.GetDecimal(iznos_p);
recXNar.naruceno = reader.GetDecimal(naruceno);
recXNar.narudzba = reader.GetDecimal(narudzba);
recXNar.otpremnica = reader.GetDecimal(otpremnica);
recXNar.pdv = reader.GetDecimal(pdv);
recXNar.povrat_k = reader.GetDecimal(povrat_k);
recXNar.povrat_p = reader.GetDecimal(povrat_p);
recXNar.pp_id = reader.GetDecimal(pp_id);
recXNar.preporuka = reader.GetDecimal(preporuka);
recXNar.rabat = reader.GetDecimal(rabat);
recXNar.rn_id = reader.GetDecimal(rn_id);
recXNar.skart = reader.GetDecimal(skart);
recXNar.user_id = reader.GetDecimal(user_id);
recXNar.var_n = reader.GetDecimal(var_n);
recXNar.var_v = reader.GetDecimal(var_v);
recXNar.veleprodaja = reader.GetDecimal(veleprodaja);
recXNar.vraceno = reader.GetDecimal(vraceno);
recXNar.isporuka_id = reader.GetString(isporuka_id);
recXNar.otpremljeno = reader.GetString(otpremljeno);
recXNar.promjena = reader.GetString(promjena);
recXNar.rj_id = reader.GetString(rj_id);
recXNar.zakljucano = reader.GetString(zakljucano);
listXnar.Add(recXNar);
}
}
reader.Close();
}
}
return listXnar;
}
There is a better way ( You need to just do it once and it will help in future). Derive a class from DbDataReader that will take sqldatareader in the constructor:
public class CustomReader : DbDataReader
{
private readonly SqlDataReader sqlDataReader;
//Set the sqlDataReader
public CustomReader(SqlDataReader sqlDataReader)
{
this.sqlDataReader = sqlDataReader;
//Cache the names
this.CacheColumns();
}
private Dictionary<string,int> nameOrdinals = new Dictionary<string, int>();
private void CacheColumns()
{
int fieldCount= this.sqlDataReader.FieldCount;
for (int i = 0; i <= fieldCount-1; i++)
{
string name=sqlDataReader.GetName(i);
nameOrdinals.Add(name,i);
}
}
public override object this[string name]
{
get
{
int ordinal=this.nameOrdinals[name];
return this.GetValue(ordinal);
}
}
//Custom implementation
public string GetString(string name)
{
int ordinal = this.nameOrdinals[name];
return this.GetString(ordinal);
}
//Custom implementation
public string GetString(string name,string defaultValue)
{
int ordinal = this.nameOrdinals[name];
if (this.IsDBNull(ordinal))
{
return defaultValue;
}
return this.GetString(ordinal);
}
//return from sqlDataReader
public override string GetString(int ordinal)
{
return sqlDataReader.GetString(ordinal);
}
public override void Close()
{
sqlDataReader.Close();
}
So what I have done is passed the SqlDataReader in custom class that can cache the column names with the positions. Then you are free to call the Custom implementation using the delegate sqldatareader or write your own functions on top - like I have done for string. Little bit of work initially but you can put all checks here like check for DbNull etc and return default values based on that.
SqlCommand sqlCommand = new SqlCommand("select * from cats",sqlConnection);
SqlDataReader reader = sqlCommand.ExecuteReader();
CustomReader customReader = new CustomReader(reader);
List<Cat> list = new List<Cat>();
while (customReader.Read())
{
Cat cat = new Cat();
cat.Id = customReader.GetString("id");
cat.Name = customReader.GetString("name");
list.Add(cat);
}
You may need to check the names of the columns coming back so may be store in lower case and then read in lower case. Your code doesnt need to do getordinal anymore and it is much cleaner as well.
There are several ways to do this using the SqlDataReader and DataTable....
IEnumerable<DataRow> list0 = dt.AsEnumerable();
OR
List<DataRow> list1 = new List<DataRow>(dt.Select());
OR
List<DataRow> list2 = dt.AsEnumerable().ToList();
For simple examples of DataTable take a look at this.....
http://www.nakdev.somee.com/#2&2AD97ECBE2AE41D08191F6E4C773D8A9&cs
Well it turns out that the code in my first post is OK! The mistake was in my POCO definition.
This is what caused the problem :
...
private DateTime _dt_get;
public DateTime dt_get
{
get { return _dt_get; }
set { value = _dt_get; } // <-- !!! insted of set { _dt_get = value; }
}
...
Thx for any help...
I'm trying to implement a function within a Class method and I am somewhat new to C#.
Basically, I have a method that iterates through row in a database and sets values to variables. Then, if a document has been created already it updates the document, if not it creates the document. I'm trying to factor out some of the code and I don't know where to put it as it still needs a reference to my variables. I would like to factor out the repeated items in the if else statement.
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
else
{
node = TreeNode.New(className, tp);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.SetValue("DocumentCulture", "en-US");
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
In addition to refactoring your routine I'd recommend creating some extension methods to save you some typing. For example, here's the an extension for parsing your doubles:
public static class Extensions
{
public static double ToDoubleIfNotDBNull(this object item)
{
if (item is DBNULL) return 0;
return double.Parse(item.ToString());
}
}
So then your code becomes:
double avgZValue = dr["AverageZValue"].ToDoubleIfNotDBNull();
You can just refactor your code so you don't need to set the node values in different cases:
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
bool isNewNode = false;
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
}
else
{
node = TreeNode.New(className, tp);
node.SetValue("DocumentCulture", "en-US");
isNewNewNode = true;
}
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
if (isNewNode)
{
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
else
{
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
You now also don't need all of those temporary variables from dr columns since they will only be used once. Removing those will make your method much shorter and more readable.
Just create a new method and send the values as parameters.
void SetNodeValues(Node node, DataRow row)
{
string title = dr["Title"].ToString();
....
node.SetValue("Title", title);
...
}
You might be able to do it all with a for loop (untested and not match your variables)
foreach(var col in Table.Columns)
node.SetValue(col.Name, dr[col]);
If you were using an ORM, you could send an object instead of the DataRow but that is beyond the scope of this question.
autoComplete1.ServiceMethod = objdpt.LoadDpt(prefix);
aspx.cs file code.. calling loaddpt function
public string LoadDpt(string prefixtext)
{
//Functionality : AutoComplete The DepartmentName
ArrayList arlSample = new ArrayList();
arlSample = objDataAccess.GetSingleColumn("QRY_DeptName", prefixtext);
return arlSample;
//string[] strArray = arlSample.ToArray(typeof(string)) as string[];
}
above is bll file code. calling getsinglecolum function
public ArrayList GetSingleColumn(string strQuery, params object[] objValueList)
{
ArrayList arlData = new ArrayList();
try
{
string strQry;
strQry = ReadXmlvalue(strQuery, objValueList);
cmdHrm = new OleDbCommand();
cmdHrm.Connection = conHrmDb;
if (conHrmDb.State == ConnectionState.Closed)
conHrmDb.Open();
cmdHrm.CommandText = strQry;
drdHrm = cmdHrm.ExecuteReader();
while (drdHrm.Read())
{
arlData.Add(drdHrm.ToString());
}
return arlData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conHrmDb.State == ConnectionState.Open)
conHrmDb.Close();
}
}
above is dal file code.
i want to return the string to aspx.cs file..help plz
If you want to convert the ArrayList to a string array you can use:
IEnumerable<string> strings = arlSample.Cast<string>();
string[] result = strings.ToArray();
If you want to concatenate all the elements so you can return one string you should use:
string resultString = String.Concat(strings);
I am trying to loop thru the elements of an Array[] for Parameter names and Object[] for object values using the AddWithValue().
Unfortunately it is saying "Procedure or function 'sp_add_Request' expects parameter '#RequestType', which was not supplied". When I run to cursor, I can see all the parameters are supplied, I do not understand where the problem is. Please help. See code below:
object[] myValues = new Object[] { txtID.Text, ddlAmissionType.Text };
string[] paramsNames = new string[] { "#CHI", "#RequestType"};
dbConn.addData("sp_add_Request", paramsNames, myValues, lbMsg.Text);
Parent method:
public static bool addData(string storedProcName, string[] dynamicParamName, object[] aramVals, string msg)
{
for (int i = 0; i < dynamicParamName.Length; i++)
{
cmd2.Parameters.AddWithValue(dynamicParamName[i], paramVals[i]);
//cmd2.Parameters.Add(dynamicParamName[i], dynamicParamValues[i]);
try
{
if (cmd2.Connection.State == ConnectionState.Closed)
{
cmd2.Connection.Open();
int stat = cmd2.ExecuteNonQuery();
if (stat > 0)
{
res = true;
msg = "Recorded Added successfully";
cmd2.Connection.Close();
cmd2.Dispose();
}
}
}
}
You are accessing the database in your loop because the command is executed within the for loop. So you're performing your command before the 2nd parameter is added. Move the try block outside the for loop and you should be fine.
public static bool addData(string storedProcName, string[] dynamicParamName, object[] paramVals, string msg)
{
for (int i = 0; i < dynamicParamName.Length; i++)
{
cmd2.Parameters.AddWithValue(dynamicParamName[i], paramVals[i]);
//cmd2.Parameters.Add(dynamicParamName[i], dynamicParamValues[i]);
}
try
{
if (cmd2.Connection.State == ConnectionState.Closed)
{
cmd2.Connection.Open();
}
int stat = cmd2.ExecuteNonQuery();
if (stat > 0)
{
res = true;
msg = "Recorded Added successfully";
cmd2.Connection.Close();
cmd2.Dispose();
}
}
}
You may want to just go ahead and put your connection object in a using statement that way it's automatically disposed. #abatishchev's answer below shows the proper way to handle your ado objects.
Create, use and dispose new connection/command objects each time method is being called. This will use connection pooling and other performance positive techniques.
public static bool addData(string storedProcName, string[] dynamicParamName, object[] paramVals, string msg)
{
SqlParameter[] paramArr = new SqlParameter[dynamicParamName.Length];
for(int i = 0; i < dynamicParamName.Length; i++)
{
paramArr[i] = new SqlParameter(dynamicParamName[i], paramVals[i]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
//command.CommandType = CommandType.StoredProcedure ; // if needed
command.Parameters.AddRange(paramArr);
connection.Open();
return command.ExecuteNonQuery() > 0;
}
}
See MSDN: SqlParameterCollection.AddRange() method.
Also you can use LINQ:
SqlParameter[] paramArr = dynamicParamName
.Select((paramName,i) => new SqlParameter(paramName, paramVals[i]).ToArray();
or
SqlParameter[] paramArr = Enumerable.Range(0, dynamicParamName.Length - 1)
.Select(i => new SqlParameter(dynamicParamName[i], paramVals[i])
.ToArray();