Check Cookies AND Session in Same IF Statement - asp.net

I have a function that checks for Session and Cookies and redirects user based on those.
private void CheckRecruiterLogin()
{
List<string> list = new List<string>();
if (Session["Candidate"] != null ||
Request.Cookies["Candidate"] != null)
{
list = (List<string>)Session["Candidate"];
string status = list[1].ToString();
if (status.Equals("applicant") ||
Request.Cookies["Candidate"]["Status"].Equals("applicant"))
{
Response.Redirect("ApplicantHome.aspx");
}
if (status.Equals("preboarding") ||
Request.Cookies["Candidate"]["Status"].Equals("preboarding"))
{
Response.Redirect("PreboardingHome.aspx");
}
else if (status.Equals("hiring") ||
Request.Cookies["Candidate"]["Status"].Equals("hiring"))
{
Response.Redirect("HiringHome.aspx");
}
}
else if (Session["HR"] != null || Request.Cookies["HR"] != null)
{
list = (List<string>)Session["HR"];
string type = list[1].ToString();
if (type.Equals("preboarder") ||
Request.Cookies["HR"]["Type"].Equals("preboarder"))
{
Response.Redirect("PreboarderList.aspx");
}
else if (type.Equals("datamanager") ||
Request.Cookies["HR"]["Type"].Equals("datamanager"))
{
Response.Redirect("HiringList.aspx");
}
else if (type.Equals("admin") ||
Request.Cookies["HR"]["Type"].Equals("admin"))
{
Response.Redirect("AdminHome.aspx");
}
}
else if (Session["HR"] == null &&
Request.Cookies["HR"] == null)
{
Response.Redirect("index.aspx");
}
}
But the application throws a runtime exception saying Object reference not set to an instance of an object. I believe this is because there are no cookies present.
My question is: Should I separate the checking of sessions and cookies, or can I do it in one statement?
Thanks!

Your code requires both the cookie, and the session.
If this is intended, you want to change the condition to use && instead of ||.
However, it's more likely you intend the code to use session if available, and cookies if session isn't there. This is quite simply done by storing the value in a variable, and using that later:
if (Session["Candidate"] != null || Request.Cookies["Candidate"] != null)
{
var list = Session["Candidate"] as List<string>;
var status = list == null ? Request.Cookies["Candidate"]["Status"] : list[1];
if (status == "applicant")
{
...
}
...
}
That said, using cookies for security checks like this is a bad idea - they are user visible and user editable.
Also, there's no point in using Equals - just use ==. This isn't Java, .NET actually compares the value, not the reference. Although it's probably a better idea to actually do the comparison using invariant culture, case insensitive equality. There's also no point in creating new List<string> - the value is never used. Just declare the variable at the point where you already have something to fill it with.

You are directly checking that if Request has a cookie named "HR" which will throw exception if there is no cookie with this name. So you first need to check if CookieCollection have any cookie with name "HR". Here is method which checks if CookieCollection have a cookie with a given name.
if(Request.Cookies.Get("cookieNmae") !=null)
So change your if statement like this
if (Session["HR"] != null || Request.Cookies.Get("HR") !=null)

Related

Detect blank HTML form input values

When I submit a HTML form with blank data it's still going into else block below:
String n=request.getParameter("uname");
String e=request.getParameter("mail");
String p=request.getParameter("pwd");
if(n==null || e==null || p==null)
{
// ...
} else
{
// ...
}
How can I make sure that it enters the if block?
Blank submitted input values do not arrive as null. Instead, they arrive as empty string. The null only means that the input value was not submitted at all (i.e. the input field was totally absent in the form).
If you're not interested in distinguishing the presence of a specific input field in the form, then add a String#isEmpty() check to the if block.
if (n == null || n.isEmpty() || e == null || e.isEmpty() || p == null || p.isEmpty()) {
// ...
}
You could even bake a custom utility method for this.
public static boolean isEmpty(String string) {
return (string == null || string.isEmpty());
}
if (isEmpty(n) || isEmpty(e) || isEmpty(p)) {
// ...
}
You can even go a refactoring step further with help of varargs.
public static boolean isOneEmpty(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return true;
}
}
return false;
}
if (isOneEmpty(n, e, p)) {
// ...
}
If you would like to cover whitespace as well, then replace string.isEmpty() over all place by string.trim().isEmpty().
See also:
Our Servlets wiki page
How to determine which form has been submited and to validate them in a servlet
Validating numbers with Servlets and JSP
This is because uname,mail,pwd variables are not null instead these parameters contains empty strings.
i.e.
uname="";
mail="";
pwd="";
when you check whether these parameters are null or not , it results into false and your else block executes and persist the record into database.
you can create a method to check empty string(s).
public static boolean checkEmpty(String value){
if(!(value==null))
return value.isEmpty();
return true;
}
replace your if condition with this:
if(checkEmpty(n) || checkEmpty(e) || checkEmpty(p)){
}
String n=request.getParameter("uname");
if (n != null) n = n.trim();
if (n == null) n = "";
String e=request.getParameter("mail");
if(e != null) e = e.trim();
if(e == null) e = "";
String p=request.getParameter("pwd");
if(p != null) p = p.trim();
if(p == null) p = "";
//
// only process if values for all three exist
//
if((n.length() < 1) || (e.length() < 1) || (p.length() < 1))
{
// ...
} else
{
// ...
}

Can we compare two java collections with dynamic equals method?

Lets say we have a 'Client' object:
(am just mentioning the attributes and the equals method alone of the 'Client' object below!!)
public class Client {
private Long clientId;
private String clientName;
private Integer status;
//getters and setters for above attributes
.....
...
//hashCode method
....
..
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Client other = (Client) obj;
if (clientId == null) {
if (other.clientId != null)
return false;
} else if (!clientId.equals(other.clientId))
return false;
if (clientName == null) {
if (other.clientName != null)
return false;
} else if (!clientName.equals(other.clientName))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
}
From the above equals method itz clear that 'two' client objects are said to be equal if all the attributes of the two objects are identical.
Now assume a scenario where I need to compare two collections(named say incomingClients and existingClients) of Client objects.
The first collection(Collection incomingClients) was generated after reading the 'client' data from a csv/xls file.
The second collection(Collection existingClients) contains, all the existing clients currently in the system.
I can do the following code (using apache CollectionUtils)to get the 'common' clients.
Collection<Client> commonClients = (Collection<Client>)CollectionUtils.intersection(incomingClients,existingClients);
Now with the below code I can remove these commonClients from both the collections.
incomingClients.removeAll(commonClients);
existingClients.removeAll(commonClients);
The intention of removing the 'common clients objects' was that, we dont need to do 'any processing' for these records,
as we are really not at all interested in those records.
Now how can I figure out which are the entirely 'new clients' in the 'Collection incomingClients' collection?
(When I say 'new' it means a client having a new 'clientId' which doesnt exist in the 'Collection existingClients')
Also, how can I figure out which are the clients which needs 'modification'
(When I say 'modification' it means that the 'Collection incomingClients' and Collection existingClients'
have the same clientId, but, say, different 'clientName')
I know that we can do the normal 'for' loop('check below') to figure out the 'new'/'modification needed' clients.
But I thought of writing 'something new', whether we can achieve this using some classes/function in the 'Apache CollectionUtils' package.
Collection<Client> newClients = new ArrayList<Client>();
Collection<Client> toBeModifiedClients = new ArrayList<Client>();
boolean foundClient = false;
Client client = null;
for(Client incomingClient :incomingClients){
foundClient = false;
for(Client existingClient : existingClients){
if(existingClient.getClientId().equals(incomingClient.getClientId())){
client = existingClient;
foundClient = true;
break;
}
}
if(foundClient){
toBeModifiedClients.add(client);
}else{
//not found in existing. so this is completely new
newClients.add(incomingClient);
}
}
Am I 'complicating' a simple stuff??
Any thoughts??
First, yes, you are complicating "simple stuff". Your entire question could be summarized as follows:
Given collections A and B, how can I get the following using CollectionUtils:
A-B, using a particular function that determines equality
A∩B, using a particular function that determines equality
So, yes. CollectionUtils has what you need. Look at CollectionUtils.select().

Session Variables and List Object not Updating Correctly

I should be able to figure this out, but I've been fighting with it for quite a while now.
I have a popup page that has several available requests that a user can select from. Based upon the page that the user is accessing, there could be one request or multiple requests available for that user. The single and multiple request are both saved on different session variables.
I need to know the single request that the user selected at the beginning of the process. It works fine except when the user is allowed to add multiple requests, the single request session variable is also updated.
For example, single request variable has "Florida"; then, the user reaches the multiple request page and adds GA and LA to the multiple request session variable. The single request variable is also updated to include GA and LA even though the flag is false and never reached that line. I don't want it to be updated. I need that single request to be available at all the time, so the user can see it if and when requested.
Here is a sample code where the issue is happening:
List<Request> temp = new List<Request>();
List<Request> mySearchRequest = new List<Request>();
List<Request> listSingleRequest = new List<Request>();
if (SessionWrapper.currentRequest.AvailableRequests != null)
{
mySearchRequest = (List<Request>)SessionWrapper.currentRequest.AvailableRequests;
}
if (SessionWrapper.currentRequest.MultipleRequests != null)
{
temp = (List<Request>)SessionWrapper.currentRequest.MultipleRequests;
var test = temp.Find(delegate(Request req) { return req.RequestId == id && req.Desc == description; });
// Checking if we have on the container already
if (mySearchRequest.Any(r => r.RequestId == id && r.Desc == description) == false)
{
mySearchRequest.Add(test);
if (SessionWrapper.currentRequest.SingleRequest == true && mySearchRequest.Count() == 1)
{
listSingleRequest.Add(test);
SessionWrapper.currentRequest.singleRequest = listSingleRequest ;
listSingleRequest = null;
}
}
}
//Set multiple request session here
Your help is greatly appreciated.
Thanks,
JF
After playing around with it almost all night, I was able to fix it. I am not sure if that is the most efficient way of doing it, but it works for now.
if (SessionWrapper.currentRequest.MultipleRequests != null)
{
temp = (List<Request>)SessionWrapper.currentRequest.MultipleRequests;
var test = temp.Find(delegate(Request req) { return req.RequestId == id && req.Desc == description; });
// Checking if we have on the container already
if (mySearchRequest.Any(r => r.RequestId == id && r.Desc == description) == false)
{
mySearchRequest.Add(test);
if (SessionWrapper.currentRequest.SingleRequestPage == true && mySearchRequest.Count() == 1)
{
foreach (var item in test)
{
//Create a new request object and add it to the list
Request request = new Request();
request.RequestId == item.RequestId;
request.Description == item.Description;
listSingleRequest.Add(request);
}
SessionWrapper.currentRequest.singleRequest = listSingleRequest ;
listSingleRequest = null;
}
}
}
if (SessionWrapper.currentRequest.singleRequest != null)
{
tempRequest = SessionWrapper.currentRequest.singleRequest.ToList();
foreach (var test in tempRequest)
{
Request request = new Request();
request.RequestId == item.RequestId;
request.Description == item.Description;
listSingleRequest.Add(request);
}
SessionWrapper.currentRequest.ViewRequest = listSingleRequest;
listSingleRequest = null;
}

Linq to XML single or default

I am querying an xml and i am storing the results using singleordefault
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
Debug.WriteLine("2");
var resultquery = query.SingleOrDefault();
now this line: var resultquery = query.SingleOrDefault(); works fine if it found in the xml file. However, i have a case where my query will result in a null. If i have no value, it would make an entry in the xml file and my query obviously results in null. My question is how do i cater for this without causing my programe to crash. obviously, singleordefault() doesnt work.
***************** EDITED *************************
I read what everyone said so far and it make sense but i am still having a problem.
if (query.Count() == 0)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
if (query == null)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
var resultquery = query.SingleOrDefault();
if (resultquery == null)
{
Debug.WriteLine("NULL Result");
}
else
{
Debug.WriteLine("NOT NULL");
}
I am getting a System.NullReferenceException error when the first part of the if statement is true. One user said to do this: var resultquery = query.SingleOrDefault(); then use my if..else statement to do the comparison. However i am getting the error at the point of assign query.singleofdefault() to resultquery. So i am lost.. hope someone can help. thank you
what i am trying to understand is this. the documentation states if the result query is 0 it will give a default value, if it is not, it will be a single value. so why doesnt this give a default value? [taken from the comments]
null is the default value for reference types. Apparently AllowancePaid is a reference type (a custom class).
What is the value you want when the there is no value found.
You could either do:
if (resultquery == null) {
// Logic for No result
} else {
// Logic for result found
}
Or you could force a default value
eg.
var resultquery = query.SingleOrDefault() ?? new AllowancePaid();
UPDATE
From the comments posted it appears that the null reference exception is actually caused within the query itself rather than by the assignment to resultquery and use of later.
This updated query should solve the issue
var query = from nm in xelement.Descendants("EmployeeFinance")
where nm.Element("EmpPersonal_Id") != null
&& (int)nm.Element("EmpPersonal_Id") == empID
&& nm.Element("Allow-GradeTax") != null
&& nm.Element("Allow-GradeTax").Elements("Amount") != null
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
var resultquery = query.SingleOrDefault();
if (resultquery == null) {
Debug.WriteLine("NULL Result");
} else {
// Logic here
}

What is the different between stringvariable != NullValue.String and !string.IsNullOrEmpty(stringvariable) in asp.net?

Is there any different between stringvariable != NullValue.String and !string.IsNullOrEmpty(stringvariable) in asp.net ? then which is best ?
The first tests that the string isn't "".
As strings can be null (because they are actually references) this test could fail.
By using IsNullOrEmpty you are wrapping:
if (string != null && string.Length > 0)
in one test.
IsNullOrEmpty is implemented like:
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
So it checks both an empty string, and a null string. (Where is NullValue.String defined, I cannot seem to find a reference to it in any docs, but I assume it's eiter String.Empty or "null", so your first check only checks for one of these conditions.)
.Net4 has a new function called IsNullOrWhiteSpace(string value) which also returns true if the string contains only white space.

Resources