how to get the xtragrid filtered and sorted datasource? - datasource

I have an xtraGrid control (v12.1) binded to a bindingSource, this last gets its data from a LINQ to entities query (EF4.3.1), the end user can filter and sort the gridView, I have a Stimulsoft report that shows the content of the gridView when the user clicks on a PrintListButton, how to get the xtragrid filtered and sorted datasource, in order to attach it to the report?
Thanks.

var data = GetDataView(xtraGridControl1);
report.RegData("List", data.ToTable());
public DataView GetDataView(GridControl gc)
{
DataView dv = null;
if (gc.FocusedView != null && gc.FocusedView.DataSource != null)
{
var view = (ColumnView)gc.FocusedView;
var currentList = listBindingSource.List.CopyToDataTable().DefaultView; //(DataView)
var filterExpression = GetFilterExpression(view);
var sortExpression = GetSortExpression(view);
var currentFilter = currentList.RowFilter;
//create a new data view
dv = new DataView(currentList.Table) {Sort = sortExpression};
if (filterExpression != String.Empty)
{
if (currentFilter != String.Empty)
{
currentFilter += " AND ";
}
currentFilter += filterExpression;
}
dv.RowFilter = currentFilter;
}
return dv;
}
public string GetFilterExpression(ColumnView view)
{
var expression = String.Empty;
if (view.ActiveFilter != null && view.ActiveFilterEnabled
&& view.ActiveFilter.Expression != String.Empty)
{
expression = view.ActiveFilter.Expression;
}
return expression;
}
public string GetSortExpression(ColumnView view)
{
var expression = String.Empty;
foreach (GridColumnSortInfo info in view.SortInfo)
{
expression += string.Format("[{0}]", info.Column.FieldName);
if (info.SortOrder == DevExpress.Data.ColumnSortOrder.Descending)
expression += " DESC";
else
expression += " ASC";
expression += ", ";
}
return expression.TrimEnd(',', ' ');
}

Related

Pdf file renaming and deleting not working in Android 10 using MediaStore

I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....

SQL injection error in Dynamic SQL with prepared statement

I my application we are collection some user inputs from UI and based on those values we are generating dynamic SQLs with different 'Where' conditions to query data.
It is found that that piece of code has some SQL injection flaw.
public void filter(String strSerialNumberLogic, String strSerialNumber1,
String strSerialNumber2, String strCreationDateLogic,
long lngCreationDate1, long lngCreationDate2,
String strTypeNumbers, String strTitles, long lngLoc)
throws SQLException, ClassNotFoundException {
StringBuffer strWhere = new StringBuffer();
List paramList = new ArrayList();
String arrTypeNumbers[];
String arrTitles[];
int i;
boolean bolHit;
if (!strTypeNumbers.equals("") || !strTitles.equals("")) {
arrTypeNumbers = strTypeNumbers.split(",");
arrTitles = strTitles.split(",");
bolHit = false;
strWhere.append("(");
for (i = 0; i < arrTypeNumbers.length; i++) {
if (arrTypeNumbers[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NUMBER = ?");
paramList.add(arrTypeNumbers[i]);
}
}
for (i = 0; i < arrTitles.length; i++) {
if (arrTitles[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NAME = ?");
paramList.add(arrTitles[i]);
}
}
strWhere.append(") ");
}
if (!strSerialNumber1.equals("")) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_NO " + strSerialNumberLogic + " ? ");
paramList.add(strSerialNumber1);
if (strSerialNumberLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(strSerialNumber2);
}
}
if (lngCreationDate1 != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_CREATION_DATE " + strCreationDateLogic + " ? ");
paramList.add(Long.toString(lngCreationDate1));
if (strCreationDateLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(Long.toString(lngCreationDate2));
}
}
if (lngLoc != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_LOCATION = ? ");
paramList.add(Long.toString(lngLoc));
}
String finalQuery = "";
if (!strWhere.equals("")) {
finalQuery = "WHERE " + strWhere.toString();
}
String strSQL = "SELECT * " + "FROM D990800 "
+ "LEFT JOIN D990400 ON REPORT_SYSTEM_ID ||" + " REPORT_NO = REPORT_NUMBER " + finalQuery
+ "ORDER BY REPORT_FILE_NO ASC";
System.out.println("strSQL:" + strSQL );
System.out.println("paramList:" + paramList );
Connection conn = ConnectionFactory.instance().getConnection();
PreparedStatement preparedStatement = null;
preparedStatement = conn.prepareStatement(strSQL);
for (int index = 0; index < paramList.size(); index++) {
String param = (String) paramList.get(index);
if (isParsableInt(param)) {
preparedStatement.setInt(index+1, Integer.parseInt(param));
} else {
preparedStatement.setString(index+1, param);
}
}
ResultSet rsReports = preparedStatement.executeQuery();
buildCollection(rsReports);
rsReports.close();
preparedStatement.close();
conn.close();
}
How did you come to the conclusion that you have SQL injection in this code? That would help clearing that up.
Anyway, looking at your code it seems that both strSerialNumberLogic and strCreationDateLogic are variables that comes from an external source, and are concatinated in a way that allows SQL to be injected. If this external source is the user, SQL injection can be executed. If not, than this is probably a false positive. I would improve the code anyway by chaning the logic variables turning them into Enums.

How to handle null data when null is returned

I have the code below that is returning data for me. If result equals "Success" then there is data. I am not getting any data
back but getting a null. Data is diplayed on a web grid and when the webgrid sees that the data is Null, the page crashes.
How can I handle null from here?
public Chemicalsdetails GetChemicalDataGeneratedForMonth(string branchcode, string departmentnumber, string previousMonth, string currentMonth)
{
string result = string.Empty;
result = _chemmeterprocessor.CopyPreviousMonthData(branchcode, departmentnumber, previousMonth, currentMonth);
Chemicalsdetails objChem = null;
if (result == "Success")
{
objChem = new Chemicalsdetails();
List<Chemicaltransactiondto> objAllData = new List<Chemicaltransactiondto>();
objAllData = _chemmeterprocessor.GetAllChemicalEntries(branchcode, departmentnumber, currentMonth);
objChem.GetAllChemicalsInformation = objAllData;
}
else
{
Chemicalsdetails objNoData = new Chemicalsdetails();
}
return objChem;
}
Check for null after you retrieve your data.
public Chemicalsdetails GetChemicalDataGeneratedForMonth(string branchcode, string departmentnumber, string previousMonth, string currentMonth)
{
string result = string.Empty;
result = _chemmeterprocessor.CopyPreviousMonthData(branchcode, departmentnumber, previousMonth, currentMonth);
Chemicalsdetails objChem = null;
List<Chemicaltransactiondto> objAllData = new List<Chemicaltransactiondto>();
//****Check for "Success"
if (result == "Success")
{
//****Retrieve chemical data
objAllData = _chemmeterprocessor.GetAllChemicalEntries(branchcode, departmentnumber, currentMonth);
//****End Retrieve chemical data
}
//****Check for non-null data.
if ((result == "Success") && (objAllData!=null))
{
objChem = new Chemicalsdetails();
objChem.GetAllChemicalsInformation = objAllData;
}
else
{
Chemicalsdetails objNoData = new Chemicalsdetails();
}
return objChem;
}

Error: Only primitive types or enumeration types are supported in this context

[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.

How to get modified values from dojo table

I have a Dojo table with list of key value pairs. Both fields are editable, once a value is modified i am doing:
var items = grid.selection.getSelected();
However, the modified value is not picked up only the old value is picked.
I tried the following:
dojo.parser.parse()
dojo.parser.instantiate([dojo.byId("tableDiv")]);
but none of them worked. Can any one sugggest a solution for this.
function getAllItems() {
var returnData = "";
//dojo.parser.parse();
//dojo.parser.instantiate([dojo.byId("tableDiv")]);
//grid._refresh();
var items = grid.selection.getSelected();
function gotItems(items, request) {
var i;
for (i = 0; i < items.length; i++) {
var item = items[i];
var paramName = grid.store.getValues(item, "paramName");
var paramValue = grid.store.getValues(item, "paramValue");
if (returnData == "") {
returnData = paramName + "&" + paramValue;
} else {
returnData = returnData + "#" + paramName + "&"
+ paramValue;
} document.getElementById("returnData").value = returnData;
document.getElementById("successFlag").value = "true";
}
}
//Called when loop fails
function fetchFailed(error, request) {
alert("Error reading table data");
}
//Fetch the data.
jsonStore.fetch({
onComplete : gotItems,
onError : fetchFailed
});
}