Blackberry app very slow why using Sqlite Queries in loop - sqlite

I am working on bb app , app is complete but its very slow while selecting data from sqlite ,I am not able to find any solution to boost up the performance, please see code below
for(int a=0;a<200;a++){
retrieveCode(selectQuery);
}
where
public String retrieveCode(String query)
{
String s = "";
Vector v = new Vector();
try
{
g.vec_Result = new Vector();
// Read in all records from the Category table
Statement statement = _db.createStatement(query);//"SELECT * FROM samples"
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
// Iterate through the result set. For each row, create a new
// Category object and add it to the hash table.
while(cursor.next())
{
row = cursor.getRow();
s = row.getString(0);
v.addElement(vmd);
}
statement.close();
cursor.close();
}
catch(DatabaseException dbe)
{
g.errorDialog(dbe.toString());
}
catch(DataTypeException dte)
{
g.errorDialog(dte.toString());
}
s = v.firstElement().toString();
return s;
}
I am developing for OS5.0 , please help

Related

I have a "Upload Record" PXAction to load records to grid and release these records

I have a custom PXbutton called UploadRecords, when I click this button I should populate the grid with records and release the records.
Release Action is pressed in the UploadRecords action delegate. The problem I get with this code is, the code here function properly for less records by release action but when passes thousands of records to release, it takes huge time(> 30 min.) and show the error like Execution timeout.
suggest me to avoid more execution time and release the records fastly.
namespace PX.Objects.AR
{
public class ARPriceWorksheetMaint_Extension : PXGraphExtension<ARPriceWorksheetMaint>
{
//public class string_R112 : Constant<string>
//{
// public string_R112()
// : base("4E5CCAFC-0957-4DB3-A4DA-2A24EA700047")
// {
// }
//}
public class string_R112 : Constant<string>
{
public string_R112()
: base("EA")
{
}
}
public PXSelectJoin<InventoryItem, InnerJoin<CSAnswers, On<InventoryItem.noteID, Equal<CSAnswers.refNoteID>>,
LeftJoin<INItemCost, On<InventoryItem.inventoryID, Equal<INItemCost.inventoryID>>>>,
Where<InventoryItem.salesUnit, Equal<string_R112>>> records;
public PXAction<ARPriceWorksheet> uploadRecord;
[PXUIField(DisplayName = "Upload Records", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
[PXButton]
public IEnumerable UploadRecord(PXAdapter adapter)
{
using (PXTransactionScope ts = new PXTransactionScope())
{
foreach (PXResult<InventoryItem, CSAnswers, INItemCost> res in records.Select())
{
InventoryItem invItem = (InventoryItem)res;
INItemCost itemCost = (INItemCost)res;
CSAnswers csAnswer = (CSAnswers)res;
ARPriceWorksheetDetail gridDetail = new ARPriceWorksheetDetail();
gridDetail.PriceType = PriceTypeList.CustomerPriceClass;
gridDetail.PriceCode = csAnswer.AttributeID;
gridDetail.AlternateID = "";
gridDetail.InventoryID = invItem.InventoryID;
gridDetail.Description = invItem.Descr;
gridDetail.UOM = "EA";
gridDetail.SiteID = 6;
InventoryItemExt invExt = PXCache<InventoryItem>.GetExtension<InventoryItemExt>(invItem);
decimal y;
if (decimal.TryParse(csAnswer.Value, out y))
{
y = decimal.Parse(csAnswer.Value);
}
else
y = decimal.Parse(csAnswer.Value.Replace(" ", ""));
gridDetail.CurrentPrice = y; //(invExt.UsrMarketCost ?? 0m) * (Math.Round(y / 100, 2));
gridDetail.PendingPrice = y; // (invExt.UsrMarketCost ?? 0m)* (Math.Round( y/ 100, 2));
gridDetail.TaxID = null;
Base.Details.Update(gridDetail);
}
ts.Complete();
}
Base.Document.Current.Hold = false;
using (PXTransactionScope ts = new PXTransactionScope())
{
Base.Release.Press();
ts.Complete();
}
List<ARPriceWorksheet> lst = new List<ARPriceWorksheet>
{
Base.Document.Current
};
return lst;
}
protected void ARPriceWorksheet_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected InvokeBaseHandler)
{
if (InvokeBaseHandler != null)
InvokeBaseHandler(cache, e);
var row = (ARPriceWorksheet)e.Row;
uploadRecord.SetEnabled(row.Status != SPWorksheetStatus.Released);
}
}
}
First, Do you need them all to be in a single transaction scope? This would revert all changes if there is an exception in any. If you need to have them all committed without any errors rather than each record, you would have to perform the updates this way.
I would suggest though moving your process to a custom processing screen. This way you can load the records, select one or many, and use the processing engine built into Acumatica to handle the process, rather than a single button click action. Here is an example: https://www.acumatica.com/blog/creating-custom-processing-screens-in-acumatica/
Based on the feedback that it must be all in a single transaction scope and thousands of records, I can only see two optimizations that may assist. First is increasing the Timeout as explained in this blog post. https://acumaticaclouderp.blogspot.com/2017/12/acumatica-snapshots-uploading-and.html
Next I would load all records into memory first and then loop through them with a ToList(). That might save you time as it should pull all records at once rather than once for each record.
going from
foreach (PXResult<InventoryItem, CSAnswers, INItemCost> res in records.Select())
to
var recordList = records.Select().ToList();
foreach (PXResult<InventoryItem, CSAnswers, INItemCost> res in recordList)

Dictionary and condition

I have been working on an assignment in which I have to upload some records from a file to Dictionary and manipulate.
Actually file have number of record with same invoice number and different tax values and I have to add all those values and make it only one invoice
what I'm trying to do
I'm passing values from a foreach loop to a function which check if the dictionary is empty so it will simply add first record and on second call it will check weather any record in dictionary have same invoice number so it will sum and update current tax value to one already added,
what I'm getting
when I pass 2nd value (and so on) the previous value of last entry in dictionary some how update itself with current value before even comparing which I don't want.
public jd_records jd = new jd_records();
Dictionary<int, jd_records> jdValues = new Dictionary<int, jd_records>();
//Calling values with loop while jd is a publicly declared object of class jd_records
foreach (DataRow dr in jddt.Rows)
{
//jd_records jdPass = new jd_records();
jd.supplierName = dr["Supplier"].ToString();
jd.supplierNTN = dr["Supplier NTN"].ToString();
jd.invoiceNo = dr["JDE Invoice Number"].ToString();
jd.invoiceDate = DateTime.Parse(dr["JDE Invoice Date"].ToString());
if (dr["Taxable Amount"].ToString().Equals(""))
{ jd.taxable = 0; }
else
{ jd.taxable = float.Parse(dr["Taxable Amount"].ToString()); }
if (dr["Tax To Pay"].ToString().Equals(""))
{ jd.tax = 0; }
else
{ jd.tax = float.Parse(dr["Tax To Pay"].ToString()); }
jdRecordCheck();
}
called function
public void jdRecordCheck()
{
if (jdValues.Count < 1)
{
jdValues.Add(0, jd);
}
else //previous record values (at key 0) changes to new jd value when come to this else part on execution
{
foreach (KeyValuePair<int,jd_records> jdVal in jdValues)
{
if ((jdVal.Value.supplierNTN.Equals(jd.supplierNTN)) && (jdVal.Value.invoiceNo.Equals(jd.invoiceNo)))
{
jdVal.Value.tax = jdVal.Value.tax + jd.tax;
jdVal.Value.taxable = jdVal.Value.taxable + jd.taxable;
jdValues[jdVal.Key] = jdVal.Value;
}
else
{
jdValues.Add(jdVal.Key + 1, jd);
}
}
}
}
I'll be very thankful if anyone helps.
Seems to me this would be much easier to do with Linq, which contains functions for grouping and summing.
List<jd_records> result = jddt.Rows
.GroupBy(jd => jd.invoiceNo)
.Select(jd => new jd_records
{
invoiceNo = jd.invoiceNo,
totalTax = jd.Sum(d => d.tax)
}).ToList();

Save SAP RFC structure to MSSQL table?

Recently i am working on a project that required to fetch the data from SAP table to MICROSOFT SQL table ,I have completed the connection part and i also pulled the SAP structure values into ASP.NET.
My question is how to save the structure into Sql table ?
here is my code ;
RfcDestination mydestination = RfcDestinationManager.GetDestination("rfcecp");
RfcRepository myrepository = mydestination.Repository;
IRfcFunction EHSIMSFM = myrepository.CreateFunction("ZEHSIMS");
EHSIMSFM.Invoke(mydestination);
IRfcTable positable = EHSIMSFM.GetTable("POSITIONTAB1");
if (positable.RowCount > 0)"THIS IS THE SAP STRUCTURE WITH ROW COUNT '300'."
{
posid.Text = "working";
}
else
{
posid.Text = "notworking";
}
}
catch (Exception ej)
{
posid.Text = ej.Message;
}
You can gather all the information from a returning IRfcTable via NCo 3 SAP Connector.
Here is the way to traverse each row (IRfcStructure) from the IRfcTable object..
foreach (IRfcStructure row in rfcTable)
{
for (int element = 0; element < rfcTable.ElementCount; element++)
{
RfcElementMetadata metadata = rfcTable.GetElementMetadata(element);
// row.GetString(metadata.Name); // get value from row's field
}
// You have your data from a row here..
}
Example: Here is the code which converts IRfcTable into DataTable.
public static DataTable CreateDataTable(IRfcTable rfcTable)
{
var dataTable = new DataTable();
for (int element = 0; element < rfcTable.ElementCount; element++)
{
RfcElementMetadata metadata = rfcTable.GetElementMetadata(element);
dataTable.Columns.Add(metadata.Name);
}
foreach (IRfcStructure row in rfcTable)
{
DataRow newRow = dataTable.NewRow();
for (int element = 0; element < rfcTable.ElementCount; element++)
{
RfcElementMetadata metadata = rfcTable.GetElementMetadata(element);
newRow[metadata.Name] = row.GetString(metadata.Name);
}
dataTable.Rows.Add(newRow);
}
return dataTable;
}
Similarly, you can add your data into MSSQL DB.

ASP.NET MySQL update multiple records

I have a web page that needs to update multiple records. This page gets all the information and then begins a transaction sending multiple UPDATE queries to the data base.
foreach row
{
Prepare the query
Hashtable Item = new Hashtable();
Item.Add("Id", Id);
Item.Add("Field1", Field1);
Item.Add("Field2", Field2);
Item.Add("Field3", Field3);
...
}
Then we launch the ytransaction
DO CHANGES()
public void execute_NonQuery_procedure_transaction(string StoredProcedure, List<Hashtable> Params)
{
using (MySqlConnection oConnection = new MySqlConnection(ConfigurationManager.AppSettings[DB]))
{
MySqlTransaction oTransaction;
bool HasErrors = false;
oConnection.Open();
oTransaction = oConnection.BeginTransaction();
try
{
MySqlCommand oCommand = new MySqlCommand(StoredProcedure, oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Transaction = oTransaction;
foreach (Hashtable hParams in Params)
{
oCommand.Parameters.Clear();
IDictionaryEnumerator en = hParams.GetEnumerator();
while (en.MoveNext())
{
oCommand.Parameters.AddWithValue("_" + en.Key.ToString(), en.Value);
oCommand.Parameters["_" + en.Key.ToString()].Direction = ParameterDirection.Input;
}
oCommand.ExecuteNonQuery();
}
}
catch (Exception e)
{
HasErrors = true;
throw e;
}
finally
{
if (HasErrors)
oTransaction.Rollback();
else
oTransaction.Commit();
oConnection.Close();
}
}
}
Is there another way to do this or this is the most efficient way?
It depends on the situation, like if you have multiple row updates or adding new rows or deleting some rows or a combination of these, which modifies the database table then, the efficient way to do this is to have Batch Update...
Please go through this link Batch Update
Hope this helps...
it looks fine to me, you could eventually do not clear the Command.Parameters list but just assign the values on following iterations but probably this leads to no visible improvements.
pay attention your throw is wrong, in C# don't use throw e; but simply throw;.

Retrieve Random Record/Row from DataBase Table Using LINQ 2 SQL

I have in DB table Called Students We make some thing like lottery to know which students are going to be the winner in some thing like game in a school
public static List<Students> GetAll()
{
List<Students> list = new List<Students>();
var query = from c in new HsInternetDBDataContext().Students
orderby c.DateCreated ascending
select c;
foreach (DAL.Student dr in query.ToList())
{
l.Add(new Quotes(dr));
}
return list;
}
what i want to do is to retrieve random student from this table
the same question are posted in another blog and i quote the answer when i post it :
public static Quotes GetRandomStudents()
{
HsInternetDBDataContext db = new HsInternetDBDataContext();
var query = from c in db.Students select c;
int count = query.Count();
if (query.Count() > 0)
{
Random r = new Random();
return new Students(query.ToList()[r.Next(0, count)]);
}
else
{
return new Students();
}
}
Hope that helps because it works with another one has the same situation

Resources