JPA named query set - linux

I'm trying to create a namedquery with a set that changes 2 fields. Below is what I tried, which isn't working. It worked fine until I added the ae.endTime and the setParameter. Can you not SET multiple things in one query?
#NamedQuery(name = AttEnt.JQL.MARK_INCOMPLETE,
query = "UPDATE AttEnt ae"
+ " SET ae.result ="
+ " Result.INCOMPLETE,"
+ " ae.endTime = :now"
+ " WHERE ae.result IS NULL")
Below is where I'm calling the query.
final EntityManager em = emf.createEntityManager();
// Mark things with no result as incomplete and endTime to current time
em.getTransaction().begin();
final Query upAtt = em.createNamedQuery(
AttEnt.JQL.MARK_INCOMPLETE);
updateAttempts.setParameter("now", (new Date()).getTime());
upAtt.executeUpdate();
em.getTransaction().commit();

Depending on how you have mapped your endTime field, you should use an overloaded variation of the setParameter method, which add the datetime information. For example:
updateAttempts.setParameter("now", (new Date()).getTime(), TemporalType.TIME);
Here more on Temporal Types.

Related

querying sqlite database using "between" with cursor

newbie here.. i have a two data sets which is "time-in", and "time-out" and i would like to query this two using "between" so that the data ive should get was the filtered on my "time-in" to my "time-out"...
this is my query data (get all data).
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db)
{
String[] columnNames =
{
HISTORY_SERIAL_NUMBER,
HISTORY_LATITUDE,
HISTORY_LONGITUDE,
HISTORY_DATE_TIME,
HISTORY_SPEED,
HISTORY_PORT
};
return (db.query(TABLE_HISTORY_FLEET_LOCATION, columnNames,null,
null,null, null, null));
}
Use rawQuery() method to prepare select statement.
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db, String timeIn, String {
String sql = "SELECT HISTORY_SERIAL_NUMBER, HISTORY_LATITUDE,"
+ " HISTORY_LONGITUDE, HISTORY_DATE_TIME, HISTORY_SPEED, HISTORY_PORT"
+ " FROM your_table_name"
+ " WHERE your_time_in_out_column BETWEEN '" + timeIn + "' AND '" + timeOut + "'";
return (db.rawQuery(sql, null));
}
You have to change your_table_name with your actual table name and your_time_in_out_column with actual column name and timeIn and timeOut variable type, values with your actual values.
While calling retrieveHistoryLocationFromLocalDatabase() method you need to pass 3 parameters SQLite database object, time-in and time-out.
PS: rawQuery() method is not recommended as it takes raw SQL statements as an argument. This poses SQL injection threat.

C# Dynamics For each giving me an error when multiple products

I'm trying to get a field to update with each line item on the invoice (without over writing what is already there), using a Query Expression to get the data that needs to be used to update the field.
So far I've been able to get this to work just fine when only 1 line item is present. But whenever I test this against multiple line items I get the " The given key was not present in the dictionary." error.
Any help or nudge in the right direction?
QueryExpression lineitem = new QueryExpression("invoicedetail");
lineitem.ColumnSet = new ColumnSet("quantity", "productid", "description");
lineitem.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, invoiceid);
EntityCollection results = server.RetrieveMultiple(lineitem);
Invoice.Attributes["aspb_bookmarksandk12educational"] = "Purchases";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "Product" + " " + "Quantity";
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
foreach (var a in results.Entities)
{
string name = a.Attributes["description"].ToString();
string quantity = a.Attributes["quantity"].ToString();
Invoice.Attributes["aspb_bookmarksandk12educational"] += " " + name + " ";
Invoice.Attributes["aspb_bookmarksandk12educational"] += quantity;
Invoice.Attributes["aspb_bookmarksandk12educational"] += "\n";
}
"The given key was not present in the dictionary."
Suggests the problem lies in the way you are trying to access attribute values and not with the multiple entities returned. When you try get an attribute value, try to check if the attribute exists before reading the value like so:
if (a.Attributes.ContainsKey("description"))
{
var name = a.Attributes["description"] as string;
}
Or even better use the SDK extension methods to help do the check and return a default value for you like so:
var name = a.GetAttributeValue<string>("description");
var quantity = a.GetAttributeValue<decimal>("quantity");

how to pass a guid as a parameter for a stored procedure

Hi I'm just learning C# and am struggling with a problem and would appreciate any help I can get.
My first problem is this, I have an aspx form that when you hit the save button it inserts data into 2 separate tables, [Transaction and TransactionDetails] both tables contain TransID fields defined as Guids. The Transaction tables Guid is also the primary key. My question is how do I insert the same guid (TransID) which is a uniqueidentifier into both tables.... then at the same time(that's my hope) I have a stored proc that needs to be run that requires that same Guid as a parameter. So in short I need the same GUID in both tables and have to pass the newly created Guid to my stored procedure.
Here's my code code so far, can you help me with what I need to add or change to make that happen.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection((System.Configuration.ConfigurationManager.ConnectionStrings["NovaConnectionString"].ConnectionString));
sc.Open();
string insertSQL;
insertSQL = "INSERT INTO [Transaction] (";
insertSQL += "TransactionID, FileNumber, TransactionDate, RegistryID, InstrumentID, TransactionTypeID, CompanyID, ";
insertSQL += "InvoiceNo, Unit, Price, DueDiligance, Legal)";
insertSQL += "VALUES (";
insertSQL += "#TransactionID, #FileNumber, #TransactionDate, #RegistryID, #InstrumentID, #TransactionTypeID, #CompanyID, ";
insertSQL += "#InvoiceNo, #Unit, #Price, #DueDiligance, #Legal)";
//string query1 = String.Format(#"Insert Into Transaction (TransactionID, FileNumber, TransactionDate, RegistryID, InstrumentID, TransactionTypeID, CompanyID, InvoiceNo, Unit, Price, DueDiligance, Legal)"
//+ " VALUES (#TransactionID, #FileNumber, #TransactionDate, #RegistryID, #InstrumentID, #TransactionTypeID, #CompanyID, #InvoiceNo, #Unit, #Price, #DueDiligance, #Legal)");
SqlCommand cmd = new SqlCommand(insertSQL, sc);
SqlCommand cmd3 = new SqlCommand("uspProcessPurchasedOffsets", sc);
cmd3.CommandType = CommandType.StoredProcedure;
//Add the parameters.
cmd.Parameters.AddWithValue("#TransactionID", Guid.NewGuid());
cmd.Parameters.AddWithValue("#FileNumber", txtFileNumber.Text);
cmd.Parameters.AddWithValue("#TransactionDate", txtTransactionCreated.Text);
cmd.Parameters.AddWithValue("#RegistryID", ddlRegistry.Text);
cmd.Parameters.AddWithValue("#InstrumentID", ddlInstrument.Text);
cmd.Parameters.AddWithValue("#TransactionTypeID", txtTransactionTypeID.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompany.Text);
cmd.Parameters.AddWithValue("#InvoiceNo", txtInvoiceNo.Text);
cmd.Parameters.AddWithValue("#Unit", txtTotalVolume.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#DueDiligance", txtDueDiligance.Text);
cmd.Parameters.AddWithValue("#Legal", txtLegal.Text);
//Parameter for stored Proc
cmd3.Parameters.Add("#TransactionID", SqlDbType.UniqueIdentifier);
cmd.ExecuteNonQuery();
string insertSQL2;
insertSQL2 = "INSERT INTO [TransactionDetails] (StartSerialNumber,VintageYear,Units)";
insertSQL2 += "VALUES (#StartSerialNumber, #VintageYear, #Units)";
SqlCommand cmd1 = new SqlCommand(insertSQL2, sc);
//Add the parameters.
cmd1.Parameters.AddWithValue("#StartSerialNumber", txtStartSerial.Text);
cmd1.Parameters.AddWithValue("#VintageYear", txtVintage.Text);
cmd1.Parameters.AddWithValue("#Units", txtVolume.Text);
cmd1.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
}
}
I think you could store the GUID in an appropriate intermediate variable and then pass the same variable to yours parameters for the storedprocedure and for the commandtext
Guid g = Guid.NewGuid();
cmd.Parameters.AddWithValue("#TransactionID", g);
.....
cmd3.Parameters.Add("#TransactionID", SqlDbType.UniqueIdentifier, 16 ).Value = g;

Subsonic 3 - Sequence contains no matching element

I need help creating a LINQ SQL with subsonic. First the basics, this works fine:
var query = (from o in bd.concelhos
orderby o.descricao
select o);
var results = query.ToList<concelhos>();
However, I want to filter out some columns and I have created the following code:
var query = (from o in bd.concelhos
orderby o.descricao
select new FilteredConcelhos { id = o.idDistrito + "/" + o.idConcelho, descricao = o.descricao });
var results = query.ToList<FilteredConcelhos>();
which errors out in the ToList method with the description "Sequence contains no matching element"
Any help would be great with this...
update:
Turns out I was missing get set attributes in the newly declared class...
Like so
public class FilteredConcelhos
{
public string id { get; set; }
public string descricao { get; set; }
}
This clears the exception, but the resulting List is still all wrong (FilteredConcelhos.id contains nothing and FilteredConcelhos.descricao contains numbers)
Can you try to first execute the ToList and the select afterwards - then the select is performed via linq 2 objects!
Have you tried to work with an anonymous type?
var query = (from o in bd.concelhos
orderby o.descricao
select new { id = o.idDistrito + "/" + o.idConcelho,
descricao = o.descricao });
var results = query.ToList();
Unfortunately, this happened to me a lot. I'm not sure about the details of how Linq 2 Object works, but if you'll call ToList on the original object, like this:
from o in bd.concelhos.ToList()
...
It should do the trick.

FullTextSqlQuery RowLimit setting defaulted when adding WHERE criteria

We are experiencing an issue where a FullTextSqlQuery is only returning the default 100 results whenever certain criteria are added in the WHERE clause. We are setting the RowLimit to int.MaxValue, and when a wide-open search is done, we are receiving the max results. It's only an issue when tacking-on CONTAINS clauses. Has anyone else seen this issue? I wasn't able to dig up anything on Google/Bing.
FullTextSqlQuery kRequest = new FullTextSqlQuery(ServerContext.Current);
kRequest.KeywordInclusion = KeywordInclusion.AnyKeyword;
kRequest.ResultTypes = ResultType.RelevantResults;
kRequest.TrimDuplicates = false;
kRequest.RowLimit = int.MaxValue;
kRequest.Timeout = 120000;
ResultTableCollection resultTbls = kRequest.Execute();
Query Code:
string query = "SELECT Title, Path, Facility, OwnerDepartment,
FacilityActiveDate, FacilityInactiveDate, ScheduledReviewDate, DocID,
Version FROM SCOPE() WHERE ";
query += "Path like '%" + site.Url + "%'";
// when it hits the else statement is an example of when it will only
// return 100 results
if (FacilitySelectedIndex == 1)
{
query += " AND Facility IS NOT NULL";
}
else
{
query += " AND CONTAINS(Facility, '\"*" + FacilityShortName.Trim() + "*\"')";
queryText.Add("Facility=" + FacilityShortName);
}
}
If I recall correctly, the RowLimit max value is actually less than int.MaxValue, only it won't tell you that. Try setting the RowLimit to some arbitrary large number that is still smaller than int.MaxValue, such as 99999

Resources