Cannot convert from object to string error - model-view-controller

Hi I have code like this :
foreach (DataRow dr in upCSV.Rows)
{
ObjectParameter getCustomField1 = new ObjectParameter("CustomField1", String.IsNullOrEmpty(dr["CustomField1"]) ? null : Convert.ToInt32(dr["CustomField1"]));
var results = ordertable.usp_AppUpdateUserData(Convert.ToInt32( getCustomField1) )
}
Here I am getting error as Cannot convert from object to string .
Here Customefield1 is of int type and it has null value. So when i debug, it is showing value for customfield1 as " ". So how can I convert this to int and pass it to my Stored procedure ?

You can cast your dr["CustomField1"] object directly to an int?:
foreach (DataRow dr in upCSV.Rows)
{
int? CustomField1 = dr["CustomField1"] as int?;
ObjectParameter getCustomField1 ;
if (CustomField1.HasValue)
{
getCustomField1 = new ObjectParameter("CustomField1", CustomField1);
}
else
{
getCustomField1 = new ObjectParameter("CustomField1", typeof(global::System.Int32));
getCustomField1.Value = DBNull.Value;
}
var results = ordertable.usp_AppUpdateUserData(getCustomField1);
}

Related

Problem two query db2 sqlserver is not print output

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

'Argument expression is not valid' when creating anonymous types dynamically

I'm creating an expression tree builder to return custom anonymous types. I tried it first with discrete types and it works ok, but using TypeBuilder to build types at runtime and pass that type to the expression tree fail with this error
'Argument expression is not valid'
here is the code I use:
this method I use to create the anonymous type
private Type CreateAnonymousType(Dictionary<string, Type> properties)
{
AssemblyName dynamicAssemblyName = new AssemblyName("MyAssembly");
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAssembly");
TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("ReturnType", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
foreach (var p in properties)
{
dynamicAnonymousType.DefineField(p.Key, p.Value, FieldAttributes.Public);
}
return dynamicAnonymousType.CreateType();
}
and here is how I create the expression tree
var cars = new List<Car>();
for (int i = 0; i < 10; i++)
{
cars.Add(new Car { Id = i, Name = "Car " + i, Age = 2010 + i });
}
IQueryable<Car> allCars = cars.AsQueryable();
var properties = new Dictionary<string, Type>
{
{ "Id", typeof(int) },
{ "Name", typeof(string) }
};
ParameterExpression x = Expression.Parameter(typeof(Car), "x");
var listMembers = properties.Select(p => Expression.Property(x, p.Key));
var returnType = CreateAnonymousType(properties);
object destObject = Activator.CreateInstance(returnType);
var listBind = listMembers.Select(p => Expression.Bind(returnType.GetField(p.Member.Name), p));
var result = Expression.New(returnType);
var initExp = Expression.MemberInit(result, listBind.ToArray());
var call = Expression.Call(typeof(Queryable), "Select",
new Type[] {
typeof(Car),
returnType
}
, Expression.Constant(allCars)
, Expression.Lambda(initExp, x));
var qResult = allCars.Provider.CreateQuery<IdName>(call);
foreach (var car in qResult)
{
Console.WriteLine(car.Id + " - " + car.Name);
}
the error happened while CreateQuery method executes
This is because call returns dynamically created ReturnType not IdName thus the exception. Additionally you cannot put such dynamic types like ReturnType as generic type parameters because compiler knows nothing about them so you should use dynamic instead so the type will be resolved at runtime:
var qResult = allCars.Provider.CreateQuery<dynamic>(call);

How can improve this Linq query expressions performance?

public bool SaveValidTicketNos(string id,string[] ticketNos, string checkType, string checkMan)
{
bool result = false;
List<Carstartlistticket>enties=new List<Carstartlistticket>();
using (var context = new MiniSysDataContext())
{
try
{
foreach (var ticketNo in ticketNos)
{
Orderticket temp = context.Orderticket.ByTicketNo(ticketNo).SingleOrDefault();
if (temp != null)
{
Ticketline ticketline= temp.Ticketline;
string currencyType = temp.CurrencyType;
float personAllowance=GetPersonCountAllowance(context,ticketline, currencyType);
Carstartlistticket carstartlistticket = new Carstartlistticket()
{
CsltId = Guid.NewGuid().ToString(),
Carstartlist = new Carstartlist(){CslId = id},
LeaveDate = temp.LeaveDate,
OnPointName = temp.OnpointName,
OffPointName = temp.OffpointName,
OutTicketMan = temp.OutBy,
TicketNo = temp.TicketNo,
ChekMan = checkMan,
Type = string.IsNullOrEmpty(checkType)?(short?)null:Convert.ToInt16(checkType),
CreatedOn = DateTime.Now,
CreatedBy = checkMan,
NumbserAllowance = personAllowance
};
enties.Add(carstartlistticket);
}
}
context.BeginTransaction();
context.Carstartlistticket.InsertAllOnSubmit(enties);
context.SubmitChanges();
bool changeStateResult=ChangeTicketState(context, ticketNos,checkMan);
if(changeStateResult)
{
context.CommitTransaction();
result = true;
}
else
{
context.RollbackTransaction();
}
}
catch (Exception e)
{
LogHelper.WriteLog(string.Format("CarstartlistService.SaveValidTicketNos({0},{1},{2},{3})",id,ticketNos,checkType,checkMan),e);
context.RollbackTransaction();
}
}
return result;
}
My code is above. I doubt these code have terrible poor performance. The poor performance in the point
Orderticket temp = context.Orderticket.ByTicketNo(ticketNo).SingleOrDefault();
,actually, I got an string array through the method args,then I want to get all data by ticketNos from database, here i use a loop,I know if i write my code like that ,there will be cause performance problem and it will lead one more time database access,how can avoid this problem and improve the code performance,for example ,geting all data by only on databse access
I forget to tell you the ORM I use ,en ,the ORM is PlinqO based NHibernate
i am looking forward to having your every answer,thank you
using plain NHibernate
var tickets = session.QueryOver<OrderTicket>()
.WhereRestrictionOn(x => x.TicketNo).IsIn(ticketNos)
.List();
short? type = null;
short typeValue;
if (!string.IsNullOrEmpty(checkType) && short.TryParse(checkType, out typeValue))
type = typeValue;
var entitiesToSave = tickets.Select(ticket => new Carstartlistticket
{
CsltId = Guid.NewGuid().ToString(),
Carstartlist = new Carstartlist() { CslId = id },
LeaveDate = ticket.LeaveDate,
OnPointName = ticket.OnpointName,
OffPointName = ticket.OffpointName,
OutTicketMan = ticket.OutBy,
TicketNo = ticket.TicketNo,
ChekMan = checkMan,
CreatedOn = DateTime.Now,
CreatedBy = checkMan,
Type = type,
NumbserAllowance = GetPersonCountAllowance(context, ticket.Ticketline, ticket.CurrencyType)
});
foreach (var entity in entitiesToSave)
{
session.Save(entity);
}
to enhance this further try to preload all needed PersonCountAllowances

Dynamic Linq to Datatable Derived Field

Is it possible to use Dynamic Linq to run a query similar to:
Select a, b, a + b as c
from MyDataTable
I have an application where the user can enter SQL statements, the results of these statements are then assigned to a DataTable. There is also the option to derive a field based on other fields. (e.g. user can say field C = a + b, or field D = A*B+10 etc).
Ideally I would like to do something similar to:
string myCalc = "Convert.ToDouble(r.ItemArray[14])+Convert.ToDouble(r.ItemArray[45])";
var parameters = from r in dt.AsEnumerable()
select (myCalc);
What I want to do in this example is add the value of column 14 to column 45 and return it. It's up to the user to decide what expression to use so the text in the select needs to be from a string, I cannot hard code the expression. The string myCalc is purely for demonstration purposes.
You could do that using a Dictionary, and a DataReader and Dynamic Queries. Here is an example based in part in Rob Connery's Massive ORM RecordToExpando:
void Main()
{
string connString = "your connection string";
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connString);
string statement = "SUM = EstimatedEffort + OriginalEstimate, Original = OriginalEstimate";
// Note: You should parse the statement so it doesn't have any updates or inserts in it.
string sql = "SELECT " + statement +" FROM Activities";
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
conn.Open();
using(conn)
{
var cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var dic = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
dic.Add(
reader.GetName(i),
DBNull.Value.Equals(reader[i]) ? null : reader[i]);
}
results.Add(dic);
}
}
foreach (var dicRow in results)
{
foreach (string key in dicRow.Keys)
{
Console.Write("Key: " + key + " Value: " + dicRow[key]);
}
Console.WriteLine();
}
}
Something like this:
void Main()
{
var dataTable = new DataTable();
dataTable.Columns.Add("a", typeof(double));
dataTable.Columns.Add("b", typeof(double));
dataTable.Rows.Add(new object[] { 10, 20 });
dataTable.Rows.Add(new object[] { 30, 40 });
string myCalc = "Convert.ToDouble(ItemArray[0]) + Convert.ToDouble(ItemArray[1])";
var query = dataTable.AsEnumerable().AsQueryable();
var result = query.Select(myCalc);
foreach (Double c in result)
{
System.Console.WriteLine(c);
}
}

DataTable that has List<string> in it

I'm using Linq to return data from an XML file to a DataTable and that works. But now I'm trying to modify the code to loop through the DataTable. I created a custom class to model the data and have a List in my model. When I loop through the DataTable to display records it displays System.Collections.Generic.List`1[System.String] instead of the actual data. I'm not sure what to search to find the answer.
Snippet:
foreach (DataRow row in tbl.Rows)
{
myList = row["myList"] + ", " + myList;
}
The myList column is the List. I hope this makes sense.
Edited:
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
hobbiesList = (List<string>)row["hobbies"];
foreach (var item in hobbiesList)
{
hobbies.Add(item.ToString());
}
hobby = string.Join(", ", hobbies.ToArray());
hobbies.Clear();
I had to do the above to get it to work. I then add hobby to my output array.

Resources