Null reference exception - asp.net

I have a function like this
public bool CheckMentorAccess()
{
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
if (intNoOfMembers > 0)
{
blnAllow = true;
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}
And then I use if like this
if ((Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
but it is throwing a null reference exception on the first line of the sample above
Can anyone help me out..

You can try
if (Session["ROLE_ID"] != null && (Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
First check that Session["ROLE_ID"] exists before you use ToString.
It is always safer to use Convert.ToString.

Well, if the stack trace only points at that line, I'd guess this is the problem:
Int32.Parse(Session["ROLE_ID"].ToString())
That will throw a NullReferenceException if Session["ROLE_ID"] returns null.
(It will throw FormatException if the value exists in the session but isn't a valid integer.)
It's possible that it's the call to CheckMentor() which is failing, of course - but then your stack trace should say so. That could fail if cSQLHelper is null, for example.

Try this - check the values you are using when you call the method:
if (Session["ROLE_ID"] != null)
{
if ((Int32.Parse(Session["ROLE_ID"]) == 3) && (CheckMentorAccess()))
{
cmbempList.Visible = true;
}
}
and check in the method
public bool CheckMentorAccess()
{
if (Session["UserID"] == null)
{
throw new NullReferenceException("UserID is null");
}
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
blnAllow = intNoOfMembers > 0;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}

Related

Oracle "UPDATE" command returns 0 rows affected in my ASP .NET application but the SQL statement itself works in PL/SQL

I have this ASP.NET project working with Oracle, I have the following code for operating the DB:
public int cmd_Execute_Orcl(string strSql, params OracleParameter[] paramArray)
{
OracleCommand myCmd = new OracleCommand();
try
{
myCmd.Connection = myOrclConn;
myCmd.CommandText = strSql;
foreach (OracleParameter temp in paramArray)
{
myCmd.Parameters.Add(temp);
}
ConnectionManage(true);
int i = myCmd.ExecuteNonQuery();
myCmd.Parameters.Clear();
return i;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myCmd.Dispose();
ConnectionManage(false);
}
}
"ConnectionManage()" turns on or off the connection, the following code is from data access layer of the program:
public string Edit_DAL(string id, string jh, string jz, string jd, string wd, string gzwz, string qxlx, string sx, string jx, string jb, string cfdd, string zjqssj, string zjzzsj, string bz)
{
string sql = "update JH set jh = :jh, jz = :jz, wd = :wd, jd = :jd, gzwz = :gzwz, qxlx = :qxlx, sx = :sx, jx = :jx, jb = :jb, cfdd = :cfdd, zjqssj = TO_DATE(:zjqssj, 'yyyy-mm-dd hh24:mi:ss'), zjzzsj = TO_DATE(:zjzzsj, 'yyyy-mm-dd hh24:mi:ss'), bz = :bz where ID = :idy";
string result = null;
{
String[] temp1 = zjqssj.Split('/');
String[] temp2 = zjzzsj.Split('/');
string tempString = "";
if (temp1[2].Length < 2)
{
temp1[2] = temp1[2].Insert(0, "0");
}
for (int i = 0; i < temp1.Length; i++)
{
if (i != 0)
{
temp1[i] = temp1[i].Insert(0, "/");
}
tempString += temp1[i].ToString();
}
zjqssj = tempString;
tempString = "";
if (temp2[2].Length < 2)
{
temp2[2] = temp2[2].Insert(0, "0");
}
for (int i = 0; i < temp2.Length; i++)
{
if (i != 0)
{
temp2[i] = temp2[i].Insert(0, "/");
}
tempString += temp2[i].ToString();
}
zjzzsj = tempString;
tempString = "";
}
OracleParameter[] pars ={
new OracleParameter(":idy",id),
new OracleParameter(":jh",jh),
new OracleParameter(":jz",jz),
new OracleParameter(":jd",jd),
new OracleParameter(":wd",wd),
new OracleParameter(":gzwz",gzwz),
new OracleParameter(":qxlx",qxlx),
new OracleParameter(":sx",sx),
new OracleParameter(":jx",jx),
new OracleParameter(":jb",jb),
new OracleParameter(":cfdd",cfdd),
new OracleParameter(":zjqssj",(zjqssj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":zjzzsj",(zjzzsj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":bz",bz)
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
result = "ok";
}
catch (Exception ex)
{
result = "no" + "=" + ex.Message + "\n" + ex.StackTrace;
}
return result;
}
Here's where the strange thing happens, when I hit this part of the code, there's no exception, it returns 0, no rows affected, all the values of the parameters are normal, with expected value, then I tried to run the command in PL/SQL and it works, the row is correctly updated, delete function is also referencing the same "cmd_Execute_Orcl" method and it works just fine, and for the other object the edit function is working perfectly, I am posting the code below:
public string Edit(string OriginalId, string EditUserAccount, string EditUserName, string EditUserMobile, string EditDeptId, string EditRoleId, string EditRoleName)
{
string sql = "update AuthUser set UserAccount=:EditUserAccount, UserName=:EditUserName, UserMobile=:EditUserMobile, DepartmentId=:EditDeptId, RID=:EditRoleId, RoleName=:EditRoleName where ID=:OriginalId";
OracleParameter[] pars ={
new OracleParameter(":EditUserAccount",EditUserAccount),
new OracleParameter(":EditUserName",EditUserName),
new OracleParameter(":EditUserMobile",EditUserMobile),
new OracleParameter(":EditDeptId",EditDeptId),
new OracleParameter(":EditRoleId",EditRoleId),
new OracleParameter(":EditRoleName",EditRoleName),
new OracleParameter(":OriginalId",OriginalId),
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
return "ok";
}
catch (Exception ex)
{
string test = ex.Message;
return "no";
}
}
In the expected table, column ID is nvarchar2 with default value of sys_guid(), column ZJQSSJ and column ZJZZSJ is of type date, all other columns are of type varchar2, I have also tried executing "COMMIT" and reformating data for date, but the same problem is still there, plz help...

Datatables Object Reference not set to instance of an object for one variable

This is my datatables serverside implementation. FilterInput contains 5 variables:
Level <- string
Message <- string
Exception <-string
StartDate <- DateTime
EndDate <- DateTime
For some reason when I run this code as it is, I will always get this error:
{System.NullReferenceException: Object reference not set to an
instance of an object.
This is referring to this line:
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.
public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
JsonResult result = new JsonResult(null);
try
{
var data = dbContext.EventLogs.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(1, "Level");
modelStructure.Add(2, "TimeStamp");
modelStructure.Add(3, "LogEvent");
modelStructure.Add(4, "Message");
modelStructure.Add(5, "MessageTemplate");
modelStructure.Add(6, "Exception");
modelStructure.Add(7, "Properties");
var StartDate = FilterInput.StartDate != default(DateTime);
var EndDate = FilterInput.EndDate != default(DateTime);
if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
(!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
(!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
(StartDate && EndDate))
{
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
}
if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
var modifiedData = data.Select(u => new EventLogsListViewModel
{
Id = u.Id,
Message = u.Message,
MessageTemplate = u.MessageTemplate,
Level = u.Level,
TimeStamp = u.TimeStamp,
Exception = u.Exception,
Properties = u.Properties,
LogEvent = u.LogEvent
});
result = this.Json(new
{
draw = Convert.ToInt32(Input.Draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Input.Order,
orderdir = Input.OrderDir
});
}
catch (Exception e)
{
logger.LogError(e, LoggingGlobals.LoadingException);
}
return result;
}
EDIT: The exception still happens even when FilterInput.Exception is not null

How to populate data related to an item from the location which is same for all items in Xamarin.forms

I am developing an xamarin.forms app ,I have various fields like Item Name ,Item Number and location ,here Location of all the items are same ,by entering names or number of the items the values are generated automatically because name and number are unique but since the location number is common is for all the items I am not able to populate correct data related to a particular field ,I am using sqlite database in my project can anyone please suggest me on what basis can I generate related values ?
Here is the code
public async void OnSearch_Location(object o, EventArgs args)
{
if (location.Text == string.Empty || location.Text == null)
{
await Navigation.PushAsync(new ListValuePage("Location", filePath,
pos, list));
}
else
{
for (int p = 0; p < list.Count; p++)
{
if (list.ElementAt(p).Aisle + "." + list.ElementAt(p).Bin +
"." + list.ElementAt(p).Level == location.Text)
{
line.Text =
Convert.ToString(list.ElementAt(p).Line_Number);
location.Text = list.ElementAt(p).Aisle + "." +
list.ElementAt(p).Bin + "." + list.ElementAt(p).Level;
item.Text = list.ElementAt(p).Item_Number;
name.Text = list.ElementAt(p).Name;
if (list.ElementAt(p).Order_Qty == 0)
{
order_uom.Text = "";
}
else
{
order_qty.Text =
Convert.ToString(list.ElementAt(p).Order_Qty);
}
order_uom.Text = list.ElementAt(p).Order_UOM;
if (list.ElementAt(p).Consumption_UOM == string.Empty ||
list.ElementAt(p).Consumption_UOM == null)
{
consume_lbl.IsVisible = false;
consume_qty.IsVisible = false;
consume_uom.IsVisible = false;
}
else
{
consume_lbl.IsVisible = true;
consume_qty.IsVisible = true;
consume_uom.IsVisible = true;
if (list.ElementAt(p).Consumption_Qty == 0)
{
consume_qty.Text = "";
}
else
{
consume_qty.Text =
Convert.ToString(list.ElementAt(p).Consumption_Qty);
}
consume_uom.Text = list.ElementAt(p).Consumption_UOM;
}
}
}
}
}

javafx checklistree output: the term inter comma

for (CheckBoxTreeItem<String> treeItem : treeItems) {
if (treeItem.isSelected()) {
if (treeItem.getValue() != null) {
konular = konular + treeItem.getValue();
}
}
}
System.out.println(konular);
hi, this code for checktreeviews ,treelist sample1 sample2...
I have any choice, output: nullSample3Sample4
I want: sample3, sample4
The Java 8 way:
String konular = treeItems
.stream()
.map(TreeItem::getValue)
.filter(value -> value != null)
.collect(Collectors.joining(", "));
Try setting your variable like this:
String konular = "";
I believe it is currently turning null into a string when you add the first new string, and thus you end up with it starting with "null".
To add the comma, you could do something like this:
for (CheckBoxTreeItem<String> treeItem : treeItems) {
if (treeItem.isSelected()) {
if (treeItem.getValue() != null) {
if(konular!=""){
konular = konular + ", ";
}
konular = konular + treeItem.getValue();
}
}
}
I'm sure it's not the cleanest way, but it should do the trick.

selecting checkbox from checkbox list on condition

i have 5 checkboxlists, and each of the checkboxlists have the same 6 checkboxes.
i have to check these checkboxlists during page_Load under certain conditions.
How do i do that.?
for (int j = 0; j < no_of_listitem; j++)
{
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = '" + employeeid[j] + "'", con);
SqlDataReader y = check.ExecuteReader();
while (y.Read())
{
if (null != y && y.HasRows)
{
string yes_or_no = y["ISGoal1"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList1.Items[j].Selected = true;
}
//else CheckBoxList1.Items[j].Selected = false;
yes_or_no = y["ISGoal2"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList2.Items[j].Selected = true;
}
//else CheckBoxList2.Items[j].Selected = false;
yes_or_no = y["ISGoal3"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList3.Items[j].Selected = true;
}
//else CheckBoxList3.Items[j].Selected = false;
yes_or_no = y["ISGoal4"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList4.Items[j].Selected = true;
}
//else CheckBoxList4.Items[j].Selected = false;
yes_or_no = y["ISGoal5"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList5.Items[j].Selected = true;
}
//else CheckBoxList5.Items[j].Selected = false;
}
}
y.Close();
}
employeeid[] contains id of 6 employees.no_of_listitems is 6 which is the list of thses 6 employee ids.
Create a list with your CheckBoxList in it. Then, replace the code with something like this:
for(int z = 1; z <= checkboxLists.Count; z++)
{
checkboxLists[z].Items[j].Selected = y["ISGoal" + z].ToString().Trim() == "yes";
}
Keep in mind though that this code is not type-safe. Normally, you'd want to avoid using string in your code and y["ISGoal"+z] might be null. If it is, the application will crash. This mean you want to make checks to make sure it's ok. Trying to make a ToString() or Trim() on null will make a NullPointerException. You might also want to change "yes" by bit in your database. It would be much more safe to work with. What if someone writes "true" instead of yes?
I hope it helps out. If you have any question, don't hesitate.

Resources