If else not working in android inside for and while loop - if-statement

public void LoadRoutine() {
TableRow tbrow0 = new TableRow(getActivity());
//String[] mStrings = new String[9];
tbrow0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow0.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String c : TimeSlotSummer) {
TextView tv0 = new TextView(getActivity());
tv0.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv0.setGravity(Gravity.CENTER);
tv0.setTextSize(12);
tv0.setHeight(40);
tv0.setWidth(76);
tv0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv0.setTextColor(Color.parseColor("#000000"));
tv0.setPadding(1, 1, 1, 1);
tv0.setText(c);
tv0.setBackgroundColor(R.id.tableRowid);
tbrow0.addView(tv0);
}
tableLayout.addView(tbrow0);
String dept = GlobalClass.userDepartment;
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getActivity());
databaseAccess.Open();
String faccode = GlobalClass.faculty_code;
Cursor cRoutine = databaseAccess.getRoutine("Sunday",dept);
if (cRoutine.getCount() == 0) {
Toast.makeText(getActivity(),"No Data in Table",Toast.LENGTH_LONG).show();
}
else{
while (cRoutine.moveToNext())
{
String[] mStrings = new String[10];
mStrings[0] = cRoutine.getString(2);
mStrings[1] = cRoutine.getString(4);
mStrings[2] = cRoutine.getString(5);
mStrings[3] = cRoutine.getString(6);
mStrings[4] = cRoutine.getString(7);
mStrings[5] = cRoutine.getString(8);
mStrings[6] = cRoutine.getString(9);
mStrings[7] = cRoutine.getString(10);
mStrings[8] = cRoutine.getString(11);
TableRow tbrow1 = new TableRow(getActivity());
tbrow1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow1.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String cls:mStrings) {
TextView tv1 = new TextView(getActivity());
tv1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv1.setGravity(Gravity.CENTER);
tv1.setTextSize(12);
tv1.setWidth(75);
tv1.setHeight(37);
tv1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv1.setPadding(1, 1, 1, 1);
tv1.setBackgroundColor(R.id.tableRowid);
tv1.setText(cls);
tv1.setTextColor(Color.parseColor("#FF0000"));
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
tbrow1.addView(tv1);
}
tableLayout.addView(tbrow1);
}
}
}
Inside the last for loop, without if-else, it works properly, but with if-else it is not working, that is apps shut down and mobile restart again.
Any one help me, I want to check some substring, then text color will change, otherwise color normal.

It would help if you posted a stack trace but if the crash occurs here:
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
The only explanation is that you get a NullPointerException on cls because tv1 is obviously not null if it did not crash before.
Use this code instead:
if(cls != null && cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));

Related

MariaDB Connector C, mysql_stmt_fetch_column() and memory corruption

I'm working on a wrapper for MariaDB Connector C. There is a typical situation when a developer doesn't know a length of a data stored in a field. As I figured out, one of the ways to obtain a real length of the field is to pass a buffer of lengths to mysql_stmt_bind_result and then to fetch each column by calling mysql_stmt_fetch_column. But I can't understand how the function mysql_stmt_fetch_column works because I'm getting a memory corruption and app abortion.
Here is how I'm trying to reach my goal
// preparations here
...
if (!mysql_stmt_execute(stmt))
{
int columnNum = mysql_stmt_field_count(stmt);
if (columnNum > 0)
{
MYSQL_RES* metadata = mysql_stmt_result_metadata(stmt);
MYSQL_FIELD* fields = mysql_fetch_fields(metadata);
MYSQL_BIND* result = new MYSQL_BIND[columnNum];
std::memset(result, 0, sizeof (MYSQL_BIND) * columnNum);
std::vector<unsigned long> lengths;
lengths.resize(columnNum);
for (int i = 0; i < columnNum; ++i)
result[i].length = &lengths[i];
if (!mysql_stmt_bind_result(stmt, result))
{
while (true)
{
int status = mysql_stmt_fetch(stmt);
if (status == 1)
{
m_lastError = mysql_stmt_error(stmt);
isOK = false;
break;
}
else if (status == MYSQL_NO_DATA)
{
isOK = true;
break;
}
for (int i = 0; i < columnNum; ++i)
{
my_bool isNull = true;
if (lengths.at(i) > 0)
{
result[i].buffer_type = fields[i].type;
result[i].is_null = &isNull;
result[i].buffer = malloc(lengths.at(i));
result[i].buffer_length = lengths.at(i);
mysql_stmt_fetch_column(stmt, result, i, 0);
if (!isNull)
{
// here I'm trying to read a result and I'm getting a valid result only from the first column
}
}
}
}
}
}
If I put an array to the mysql_stmt_fetch_column then I'm fetching the only first field valid, all other fields are garbage. If I put a single MYSQL_BIND structure to this function, then I'm getting an abortion of the app on approximately 74th field (funny thing that it's always this field). If I use another array of MYSQL_BIND then the situation is the same as the first case.
Please help me to understand how to use it correctly! Thanks
Minimal reproducible example

dao property from vb to mfc

i have implemented vb functionality in c++ i have replace below logic in c++ but it is giving issue :
i have to convert from VB to c++ and the code in c++ is crashing when getting property.
Original VB code:
For Each loTDef In aoDBUser.TableDefs
Set loProp = Nothing
On Error Resume Next
Set loProp = loTDef.Properties("Description")
If Not loProp Is Nothing Then
If loProp.Value = TEMP_TABLE Then
End If
End If
Next
New C++ code:
CString test::Property()
{
//
// OVERVIEW:
// Get the value for the given Custom Property
//
DAOProperties *pColProp = NULL;
DAOProperty *pProp = NULL;
CDaoDatabase cDBase;
cDBase.Open(CV_GetUserDatabasePath(_T("TEST.mdb")));
CString strDbVer;
DAOProperties* pPrp = 0;
DAOProperty* pRev = 0;
try
{
if ( !cDBase.IsOpen() )
return(_T(""));
DAO_CHECK(cDBase.m_pDAODatabase->get_Properties(&pPrp));
if ( pPrp != 0 )
{
COleVariant varRevVal;
COleVariant varName(_T("Description"), VT_BSTRT);
DAO_CHECK(pPrp->get_Item(varName, &pRev));//crashing going to catch
if (pRev != 0)
{
DAO_CHECK(pRev->get_Value(&varRevVal));
pRev->Release();
pRev = 0;
}
pPrp->Release();
pPrp = 0;
strDbVer = V_BSTRT(&varRevVal);
}
}
catch (...)
{
}
cDBase.Close();
}
some how it is crashing in DAO_CHECK(pPrp->get_Item(varName, &pRev));
But I cannot figure out why this occurs.

Transaction Advance Search for Sales Order in NetSuite returning Errors when otherRefNum Operator used

Any idea why the below code would return an error(Failure) for its status?
private SearchResult getTxns()
{
TransactionSearchAdvanced tsa = new TransactionSearchAdvanced();
tsa.columns = new TransactionSearchRow();
tsa.columns.basic = new TransactionSearchRowBasic();
tsa.columns.basic.tranId = new SearchColumnStringField[] { new SearchColumnStringField() };
tsa.criteria = new TransactionSearch();
tsa.criteria.basic = new TransactionSearchBasic();
tsa.criteria.basic.mainLine = new SearchBooleanField();
tsa.criteria.basic.mainLine.searchValue = true;
tsa.criteria.basic.mainLine.searchValueSpecified = true;
tsa.criteria.basic.type = new SearchEnumMultiSelectField();
tsa.criteria.basic.type.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "_salesOrder" };
tsa.criteria.basic.otherRefNum = new SearchTextNumberField();
tsa.criteria.basic.otherRefNum.#operator = SearchTextNumberFieldOperator.equalTo;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "BBnB 1001" };
SearchResult sr = _service.search(tsa);
return sr;
}
The following is the error that is returned in the results.
Status Code: INVALID_SEARCH_OPERATOR
Status Message: You need to provide a valid search field operator.
However, this operator appears in the NetSuite UI itself when I do a search. Also, I find it in the NetSuite documentation here.
I am using v2013_1_0 for the webservices version of the wsdl.
SOLUTION
Solution found to be in the last block of code. Was attempting to set otherRefNum and was referencing Type. Here is the corrected code.
private SearchResult getTxns()
{
TransactionSearchAdvanced tsa = new TransactionSearchAdvanced();
tsa.columns = new TransactionSearchRow();
tsa.columns.basic = new TransactionSearchRowBasic();
tsa.columns.basic.tranId = new SearchColumnStringField[] { new SearchColumnStringField() };
tsa.criteria = new TransactionSearch();
tsa.criteria.basic = new TransactionSearchBasic();
tsa.criteria.basic.mainLine = new SearchBooleanField();
tsa.criteria.basic.mainLine.searchValue = true;
tsa.criteria.basic.mainLine.searchValueSpecified = true;
tsa.criteria.basic.type = new SearchEnumMultiSelectField();
tsa.criteria.basic.type.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
tsa.criteria.basic.type.operatorSpecified = true;
tsa.criteria.basic.type.searchValue = new string[] { "_salesOrder" };
tsa.criteria.basic.otherRefNum = new SearchTextNumberField();
tsa.criteria.basic.otherRefNum.#operator = SearchTextNumberFieldOperator.equalTo;
tsa.criteria.basic.otherRefNum.operatorSpecified = true;
tsa.criteria.basic.otherRefNum.searchValue = "BBnB 1001";
SearchResult sr = _service.search(tsa);
return sr;
}
The problem is with your SearchEnumMultiSelectField operator. equalto is not a valid operator for this filter; you will need to use anyOf instead.
-- EDIT - Adapated from original comment --
A SearchTextNumberField does not accept an array of Strings. Instead try tsa.criteria.basic.otherRefNum.searchValue = "BBnB 1001";

Open XML Excel Cell Formatting

I am trying to export to excel using Open XML with simple formatting. Export to Excel is working. The problem is with formatting the data. I am trying to have very basic formatting. i.e. the Column names should be in bold and rest of the content in normal font. This is what I did. Please let me know where am I going wrong.
private Stylesheet GenerateStyleSheet()
{
return new Stylesheet(
new Fonts(
new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12},
new Bold(),
new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12}))
)
);
}
protected void ExportExcel(DataTable dtExport)
{
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
//"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" '"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" '"application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment; filename=Test.xlsx");
Response.Charset = "";
this.EnableViewState = false;
MemoryStream ms = new MemoryStream();
SpreadsheetDocument objSpreadsheet = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart objWorkbookPart = objSpreadsheet.AddWorkbookPart();
objWorkbookPart.Workbook = new Workbook();
WorksheetPart objSheetPart = objWorkbookPart.AddNewPart<WorksheetPart>();
objSheetPart.Worksheet = new Worksheet(new SheetData());
Sheets objSheets = objSpreadsheet.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet objSheet = new Sheet();
objSheet.Id = objSpreadsheet.WorkbookPart.GetIdOfPart(objSheetPart);
objSheet.SheetId = 1;
objSheet.Name = "mySheet";
objSheets.Append(objSheet);
WorkbookStylesPart stylesPart = objSpreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStyleSheet();
stylesPart.Stylesheet.Save();
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
for (int cols = 0; cols < dtExport.Columns.Count; cols++)
{
Cell objCell = InsertCellInWorksheet(GetColumnName(cols), 1, objSheetPart);
objCell.CellValue = new CellValue(dtExport.Columns[cols].ColumnName);
objCell.DataType = new EnumValue<CellValues>(CellValues.String);
objCell.StyleIndex = 0;
}
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
for (uint row = 0; row < dtExport.Rows.Count; row++)
{
for (int cols = 0; cols < dtExport.Columns.Count; cols++)
{
//row + 2 as we need to start adding data from second row. First row is left for header
Cell objCell = InsertCellInWorksheet(GetColumnName(cols), row + 2, objSheetPart);
objCell.CellValue = new CellValue(Convert.ToString(dtExport.Rows[Convert.ToInt32(row)][cols]));
objCell.DataType = new EnumValue<CellValues>(CellValues.String);
objCell.StyleIndex = 1;
}
}
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
objSpreadsheet.Close();
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
// If the cell already exists, return it.
private Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
string cellReference = (columnName + rowIndex.ToString());
// If the worksheet does not contain a row with the specified row index, insert one.
Row row = default(Row);
if ((sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).Count() != 0))
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).First();
}
else
{
row = new Row();
row.RowIndex = rowIndex;
sheetData.Append(row);
}
// If there is not a cell with the specified column name, insert one.
if ((row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex.ToString()).Count() > 0))
{
return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if ((string.Compare(cell.CellReference.Value, cellReference, true) > 0))
{
refCell = cell;
break; // TODO: might not be correct. Was : Exit For
}
}
Cell newCell = new Cell();
newCell.CellReference = cellReference;
row.InsertBefore(newCell, refCell);
return newCell;
}
}
It seems like you are missing a ")" after your first font creation. So then you end opp with only one font index (the default one)
Below is the code I use for exactly what you are asking for.
You might remove fills and borders and remove them from cellformat, but I had some syntax problems while writing this so I just left it when it all worked :-)
private Stylesheet GenerateStyleSheet()
{
return new Stylesheet(
new Fonts(
// Index 0 - Default font.
new Font(
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
),
new Font(
new Bold(),
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
)
),
new Fills(
// Index 0 - Default fill.
new Fill(
new PatternFill() { PatternType = PatternValues.None })
),
new Borders(
// Index 0 - Default border.
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder())
),
new CellFormats(
// Index 0 - Default cell style
new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },
new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }
)
);
}

List of windows users remotely

I would like to know how to retrieve the list of users that are logged onto a Remote machine. I can do it with qwinsta /server:xxxx, but would like to do it in C#.
check out wmi in .net under system.management.
something like:
ConnectionOptions conn = new ConnectionOptions();
conn.Authority = "ntdlmdomain:NAMEOFDOMAIN";
conn.Username = "";
conn.Password = "";
ManagementScope ms = new ManagementScope(#"\\remotecomputer\root\cimv2", conn);
ms.Connect();
ObjectQuery qry = new ObjectQuery("select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection return = search.Get();
foreach (ManagementObject rec in return)
{
Console.WriteLine("Logged in user: " + rec["UserName"].ToString());
}
You may not need the ConnectionOptions...
I ended up using the qwinsta /server:server1 command from C# -- it was much easier
thanks Ken
All this checks all 8 servers at the same time -- I put the result in sql server
but you can do what ever you want
query_citrix.bat script
cd C:.......\bin\citrix_boxes
qwinsta -server:servername or ip > servername.txt
string sAppCitrixPath = Application.StartupPath.ToString() + "\\citrix_boxes\\";
//Run Script for current citrix boxes
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = sAppCitrixPath + "query_citrix.bat";
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
if (exitCode == 0)
{
//Execute update who is on the Citrix_Boxes Currently
DirectoryInfo dic = new DirectoryInfo(sAppCitrixPath);
FileInfo[] fic = dic.GetFiles("*.txt");
for (int i = 0; i < fic.Length; i++)
{
ParseQWinStaServerFile(fic[i].FullName.ToString(), fic[i].Name.ToString().ToUpper().Replace(".TXT",""));
File.Delete(fic[i].FullName.ToString());
}
}
private void ParseQWinStaServerFile(string sLocation,string sServer)
{
using (StreamReader sr = File.OpenText(sLocation))
{
string sRecord = String.Empty;
char[] cSep = new char[] {' '};
bool bFirst = true;
while ((sRecord = sr.ReadLine()) != null)
{
if (bFirst == false)
{
string[] items = sRecord.Split(cSep, StringSplitOptions.RemoveEmptyEntries);
//Make sure all columns are present on the split for valid records
if (sRecord.Substring(19, 1) != " ") // check position of user id to see if it's their
{
//Send the user id and server name where you want to.
//here is your user
id = items[1].ToString().ToLower().Trim()
//here is your server
};
}
else
{
bFirst = false;
}
}
}
}