CreateQuery constructor with getting parameter list - list

I'm new here and this is my second question, but as the first, I have a problem already tried to solve in different ways, but have not found a solution, so I'm resorting to you, here we go.
My code:
string sql = "SELECT NEW Filial(fil.NumSequencial, fil.Numero, fil.Nome, fil.Cnpj, fil.Empresa, fil.LstUsuario)" +
" FROM Filial fil" +
" join fetch fil.LstUsuario usrFil";
IQuery query = session.CreateQuery(sql);
lstFilial = (List<Filial>)query.List<Filial>();
I've tried with and without the line "join fetch", but the error is always the same:
{"illegal syntax near collection: id [SELECT NEW Filial(fil.NumSequencial, fil.Numero, fil.Nome, fil.Cnpj, fil.Empresa, fil.LstUsuario) FROM Leitor_NFe_XML_Entidade.Filial fil\tjoin fetch fil.LstUsuario usrFil]"}
The constructor:
public Filial(long numSequencial, int numero, string nome, string cnpj, Empresa empresa, IList<Usuario> lstUsuario)
{
this.numSequencial = numSequencial;
this.numero = numero;
this.nome = nome;
this.cnpj = cnpj;
this.empresa = empresa;
this.lstUsuario = lstUsuario;
}
Am thankful since already

Related

WebMethod returning multiple line (list<>) from SQL query in WCF with Entity Framework Linq

Creating a WCF in VisualStudio 2017, I need to create a WebMethod that will return multiple rows from a SQL query. Here is the code that is not working...
code
[WebMethod]
public List<TABLE_NAME> GetAllLineInfoDetailes(string OrderNumberSM)
{
string #OrdNumLG = OrderNumberSM;
List<TABLE_NAME> OrdNo = new List<TABLE_NAME>();
using (CONNECTION_NAME pubs = new CONNECTION_NAME())
{
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber == #OrdNumLG);
foreach (TABLE_NAME OrderLine in OrdNo_LINES)
{
TABLE_NAME a = new TABLE_NAME();
a.ItemNumber = OrderLine.ItemNumber;
a.LineNumber = OrderLine.LineNumber;
a.OrderNumber = OrderLine.OrderNumber;
OrdNo.Add(a);
}
}
return OrdNo;
}
code
The foreach is giving error "Cannot convert type 'bool' to 'CONNECTION_NAME.TABLE_NAME'"
Any help with this, or a better way to return the full result set, would be appreciated.
As the error says, it's a type conversion problem.
You need to
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber = #OrdNumLG);
replace
var OrdNo_LINES = (from p in pubs.TABLE_NAME select p.OrderNumber == #OrdNumLG);
Found what will work...
[WebMethod]
public List<TABLE_NAME> GetAllLineInfoDetailes(string OrderNumberSM)
{
string #OrdNumSM = OrderNumberSM;
using (CONNECTION_NAME pubs = new CONNECTION_NAME())
{
var query = (from c in pubs.TABLE_NAME
where c.OrderNumber == #OrdNumSM
orderby c.LineNumber ascending
select c).ToList();
return query;
}
}

PQexecParams in C++, query error

I'm using pqlib with postgresql version 9.1.11
I have the following code
const char *spid = std::to_string(pid).c_str();
PGresult *res;
const char *paramValues[2] = {u->getID().c_str(), spid};
std::string table;
table = table.append("public.\"").append(Constants::USER_PATTERNS_TABLE).append("\"");
std::string param_name_pid = Constants::RELATION_TABLE_PATTERN_ID;
std::string param_name_uid = Constants::RELATION_TABLE_USER_ID;
std::string command = Constants::INSERT_COMMAND + table + " (" + param_name_uid + ", " + param_name_pid + ") VALUES ($1, $2::int)";
std::cout << "command: " << command << std::endl;
res = PQexecParams(conn, command.c_str(), 2, NULL, paramValues, NULL, NULL,0);
Where
INSERT_COMMAND = "INSERT INTO " (string)
USER_PATTERN_TABLE = "User_Patterns" (string)
RELATION_TABLE_PATTERN_ID = "pattern_id" (string)
RELATION_TABLE_USER_ID = "user_id" (string)
pid = an int
u->getID() = a string
conn = the connection to the db
The table "User_Patterns" is defined as
CREATE TABLE "User_Patterns"(
user_id TEXT references public."User" (id) ON UPDATE CASCADE ON DELETE CASCADE
,pattern_id BIGSERIAL references public."Pattern" (id) ON UPDATE CASCADE
,CONSTRAINT user_patterns_pkey PRIMARY KEY (user_id,pattern_id) -- explicit pk
)WITH (
OIDS=FALSE
);
I already have a user and a pattern loaded into their respective tables.
The command generated is :
INSERT INTO public."User_Patterns" (user_id, pattern_id) VALUES ($1, $2::int)
I also tried with $2, $2::bigint, $2::int4
The problem is:
I receive the error :
ERROR: invalid input syntax for integer: "public.""
I already use PQexecParams to store users and patterns, the only difference is that they all have text/xml fields (the only int field on patterns is a serial one and I don't store that value myself) but because the user_patterns is a relation table I need to store and int for the pattern_id.
I already read the docs for pqlib and saw the examples, both are useless.
The problem is in the lines:
const char *spid = std::to_string(pid).c_str();
const char *paramValues[2] = {u->getID().c_str(), spid};
std::to_string(pid) creates temporary string and .c_str() returns a pointer to an internal representation of this string, which is destroyed at the end of the line, resulting in a dead pointer. You may also see answer to the question
stringstream::str copy lifetime

Need help coding a CriteriaQuery "in" predicate

I have a query that I have been trying to turn into a CriteraQuery, but I don't get how to code the "IN" term of the query.
The JPA Query that works looks like this:
#NamedQuery(name = "User.fromSearchID",
query = "SELECT q FROM User q,"
+ " IN (q.data) AS s WHERE s.data LIKE :search"
+ " ORDER BY q.id")
And the entity that it works on looks like this:
#Entity
public class User {
#Id private Integer id;
#OneToMany private List<UserData> data;
... }
And the referenced entity is
#Entity
public class UserData {
#Id private Long id;
private String key;
private String data;
... }
The intended result (the NamedQuery works) is to pull out all User entities that have some match in their list of data attributes. For some reason the CriteraQuery syntax escapes my intuition. Any help?
I assume users should be unique?
Then JP QL version without rather old fashion IN is:
String searchArgument = "data1";
String query = " SELECT DISTINCT(u) " +
" FROM User u JOIN u.data ud " +
" WHERE ud.data LIKE :search ORDER BY u.id";
List<User> result =em.createQuery(query, User.class).
setParameter("search", searchArgument).getResultList();
And same via Criteria API:
String searchArgument = "data1";
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> user = cq.from(User.class);
Predicate dataLike = cb.like(user.join("data").<String>get("data"),
cb.parameter(String.class, "search"));
cq.distinct(true).select(user)
.where(dataLike)
.orderBy(cb.asc(user.get("id")));
TypedQuery<User> findUniqueUserByUserDataData = em.createQuery(cq);
findUniqueUserByUserDataData.setParameter("search", searchArgument);

WMI performance query

I am having an issue with a WMI query.
I use a WMI query to search and resume an instance in BizTalk.
When there are not that many instances (so when the data isn't that much) the query performs pretty good.
But when the data is large (about 3000 instances) the query takes about 6 - 10 seconds to execute, and this isn't tolerable.
Code is as following:
string query = "SELECT * FROM MSBTS_ServiceInstance WHERE InstanceID = \"" + OrchestrationId + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope(#"root\MicrosoftBizTalkServer"), new WqlObjectQuery(query), null);
int count = searcher.Get().Count;
if (count > 0)
{
string[] strArray = new string[count];
string[] strArray2 = new string[count];
string[] strArray3 = new string[count];
string str2 = string.Empty;
string str3 = string.Empty;
int index = 0;
foreach (ManagementObject obj2 in searcher.Get())
{
if (str2 == string.Empty)
{
str2 = obj2["HostName"].ToString();
}
strArray2[index] = obj2["ServiceClassId"].ToString();
strArray3[index] = obj2["ServiceTypeId"].ToString();
strArray[index] = obj2["InstanceID"].ToString();
str3 = str3 + string.Format(" {0}\n", obj2["InstanceID"].ToString());
index++;
}
new ManagementObject(string.Format("root\\MicrosoftBizTalkServer:MSBTS_HostQueue.HostName=\"{0}\"", str2)).InvokeMethod("ResumeServiceInstancesByID", new object[] { strArray2, strArray3, strArray, 1 });
It's the first query (Select * from MSBS_ServiceInstance..) that takes to long when te data is getting bigger.
Any ideas how I can improve this?
The platform is Windows Server 2008 Enterprise..
Thx!
It looks like you are getting all service instances for your orchestration, not just the suspended ones.
Try adding the following to your query's where clause, so that only suspended and suspended-not-resumable service instances are returned:
and (ServiceStatus = 4 or ServiceStatus = 16)
Thank you for the replies.
The reason I got that many suspended instances sometimes is by design.
Whenever a message isn't in sequence, the orchestration gets suspended until the previous message went through.
I found another way to resume the instances using the BizTalkOperations class that is installed with BizTalk:
BizTalkOperations operations = new BizTalkOperations(dataSource, initialCatalog);
foreach (Guid id in instanceIds)
{
operations.ResumeInstance(id);
}
This code is much more performant then the WMI code (and less code ^^) :)
Thanks

Select new to create complex object with nested new throws cast exception

Has anyone had this issue? I am trying to get objects from the database and create a complex poco but I get a cast issue.
The Account property on the poco message type is a poco account type and it will tell me that whatever the first field type is can't be cast to PocoAccount, so in the example below, AccountID is an int so i'll get int cant' be cast to PocoAccount.
var result = (from a in DbAccount.All()
join m in DbMessage.All() on m.AccountID equals a.AccountID
select new PocoMessage {
Account = new PocoAccount {
AccountID = a.AccountID,
FirstName = a.FirstName,
LastName = a.LastName
},
MessageID = m.MessageID,
Subject = m.Subject,
Body = m.Body
});
If found a similar post that suggested using ToList() which seems to fix the issue however it doesn't feel quite right and I haven't checked out the sql consequence.
var result = (from a in DbAccount.All().ToList()
join m in DbMessage.All().ToList() on m.AccountID equals a.AccountID
select new PocoMessage {
Account = new PocoAccount {
AccountID = a.AccountID,
FirstName = a.FirstName,
LastName = a.LastName
},
MessageID = m.MessageID,
Subject = m.Subject,
Body = m.Body
});