How to know if an HTTP request header value exists - c#

Very simple I'm sure, but driving me up the wall! There is a component that I use in my web application that identifies itself during a web request by adding the header "XYZComponent=true" - the problem I'm having is, how do you check for this in your view?
The following wont work:
if (Request.Headers["XYZComponent"].Count() > 0)
Nor this:
if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)
Both throw exceptions if the header variable has not been set. Any help would be most appreciated.

if (Request.Headers["XYZComponent"].Count() > 0)
... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:
Use this instead:
if(Request.Headers["XYZComponent"] != null)
Or if you want to treat blank or empty strings as not set then use:
if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)
The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.
A variation of your second attempt will also work:
if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))
Edit: Sorry didn't realise you were explicitly checking for the value true:
bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'

Header exists:
if (Request.Headers["XYZComponent"] != null)
or even better:
string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;
if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)
which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)
Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.
public static bool? ToBoolean(this string s)
{
bool result;
if (bool.TryParse(s, out result))
return result;
else
return null;
}
Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):
if (Request.Headers["XYZComponent"].ToBoolean() == true)

Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:
public ActionResult Index()
{
var xyzComponent = Request.Headers["xyzComponent"];
var model = new MyModel
{
IsCustomHeaderSet = (xyzComponent != null)
}
return View(model);
}

The following code should allow you to check for the existance of the header you're after in Request.Headers:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
// header is present and set to "true"
}

string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;
if "true" than true
if "false" or anything else ("fooBar") than false
or
string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);
if "true" than true
if "false" than false
else ("fooBar") than null

In dotnet core, Request.Headers["X-MyCustomHeader"] returns StringValues which will not be null. You can check the count though to make sure it found your header as follows:
var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.

Related

C# Check if a UILabel is not null not work

I have a litte problem with this if statement:
if (selectedlabel.Text!=null|| selectedlabel.Text!=""|| selectedlabel!=null)
{
basketID = int.Parse(selectedlabel.Text); //nullpointer Value Can not be null
}
Why doesn't this work?
I have set a breakpoint and I see the selectedlabel.Text is null:
You use || instead of the correct &&
if (selectedlabel != null && selectedlabel.Text != null && selectedlabel.Text != "")
{
basketID = int.Parse(selectedlabel.Text);
}
But this is more concise and works too:
if (selectedlabel != null && !String.IsNullOrEmpty(selectedlabel.Text))
{
basketID = int.Parse(selectedlabel.Text);
}
Use int.TryParse to ensure that it's a valid integer:
int basketID;
if(selectedlabel != null && int.TryParse(selectedlabel.Text, out basketID))
{
// ...
}
With C#6 you can also use the null-conditional operator:
int basketID;
if(int.TryParse(selectedlabel?.Text, out basketID))
{
// ...
}
First of all you should check for nulls (because you're trying to access object's instance fields/properties) :
if(selectedlabel != null)
// or
if(!ReferenceEquals(selectedlabel, null))
Then what you're doing is just checking if string is null or empty ( on which c# has buil-in methods ) : string.IsNullOrEmpty(selectedlabel.Text)
Now you just have to connect these using && operator which checks if both are true, but fails if first check is false. Knowing that it will fall back when first condition is not met you can combine this into :
if (!ReferenceEquals(selectedlabel, null) && !string.IsNullOrEmpty(selectedlabel.Text))
{
// your code here
}
But another issue is basketID = int.Parse(selectedlabel.Text);. As i often says leave some margin for errors which means do not assume that user is smart ( better way! always assume that user is dumb as hell ) so instead of putting a number, user will input something like "please enter number 123 here" and it will kill your application.
To get rid of this just TryParse instead:
int.TryParse(selectedlabel.Text, out basketID);
Okay so combining ALL of the above, the result should be something like :
if (!ReferenceEquals(selectedlabel, null) && !string.IsNullOrEmpty(selectedlabel.Text))
{
if(!int.TryParse(selectedlabel.Text, out basketID))
{
// user entered text that is unconvertible to int
}
}
Change to
if (!string.IsNullOrEmpty(selectedlabel?.Text))
{
basketID = int.Parse(selectedlabel.Text);
}
your if statement should be equal to null if you want it to check for null, then it should be this
if (selectedlabel.Text==null|| selectedlabel.Text!=""|| selectedlabel!=null)
{
basketID = int.Parse(selectedlabel.Text); //nullpointer Value Can not be null
}
else it will not display the error you are trying to avoid.
hope it helps

Code optimization for null or empty check

Hi I am checking datatable row value. If the value is not null or empty then checking for the value if it is a number. Otherwise add in to the error list. If the value is null or empty then assign null.
The code is working fine but I want to check if there is any better way to do this. Any suggestions would be appreciated.
here is my code.
if (!(row.IsNull("limit") || row["limit"].ToString().Length == 0))
{
//Check if value is number
if (int.TryParse(row["limit"].ToString().Trim(), out n))
{
query.limit = Convert.ToInt32(row["limit"].ToString().Trim());
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
//if value is null then assign null
else
{
query.limit = null;
}
Few points I have to mention here:
By using int.TryParse to parse the row["limit"] you will get the converted value in the out parameter, then you need not convert the same again to an integer using Convert.ToInt32, use the out parameter instead.
The first if can be simplified using NullConditional operators(?.).
There may be chances for getting row as null, in such cases, you need to check for null before accessing row["limit"] otherwise NullReference will be the result
I think it will be more clear and simple if you do like this:
if (row != null && row["limit"]?.ToString() != "") // means row["limit"] definitely has some value
{
int currentLimit = 0;
if (int.TryParse(row["limit"].ToString().Trim(), out currentLimit))
{
query.limit = currentLimit ;
}
else
{
errorList.Add("limit: Value:" + row["limit"].ToString());
}
}
else
{
query.limit = null;
}
If you are not using c# 6 then row["limit"]?.ToString() will not work in this case you have to use the condition as like this:
if (row != null && row["limit"] != null && row["limit"].ToString() != "")

Property value is not valid typed data set

I am using typed data set in my application and I have a data table with two columns which are of System.Int32.AllowDBNULL = true and NULLVALUE = throw exception and default value = 1. I am using this property of datatable in my code like this:
if (rr.ForenameStatus != -1 && rr.ForenameStatus == 0)
{
}
but I am getting this error:
The value for column 'ForenameStatus' in table 'Registrant' is DBNull.
I tried to change NULLVALUE of column to NULL or empty in dataset properties but I get error:
property value is not valid
I tried using this:
if (rr.ForenameStatus != System.DBNull.Value && rr.ForenameStatus == 0)
{
}
but It says Operator != can not be applied to operands of int and dbnull
Please suggest me solution to this.
Set AllowDBNULL = true and call IsForenameStatusNull method to check on NULL value.
Try this:
if (rr.ForenameStatus.ToString()!="" && rr.ForenameStatus == 0)
{
}
This is as an alternative. You may try converting the int value to string and compare against empty string to identify the nulls.

Why is the following c# win forms validation method not working?

I have a validation method with 5 validation elements to it, 4 of which work as intended but 1 does not, question is why not?
The issue I have is with Validating "CompetitionCourse". I want the IsValid to be true only if the combobox cbCourseRound1 is not blank. At the moment this is validating regardless of this combobox being blank or populated. All other validations are working,
private bool Validate(Competition compSetup)
{
string CompetitionName = compSetup._CompetitionName;
int CompetitionFormat = compSetup._CompetitionFormatId;
string CompetitionGender = cbGenderOfCompetiton.Text;
string CompetitionMarker = cbMarker.Text;
string CompetitionCourse = cbCourseRound1.Text;
if (!CompetitionName.Equals(string.Empty) && !CompetitionGender.Equals("Mixed") && CompetitionFormat.Equals(1) && !CompetitionCourse.Equals(string.Empty) &&
((CompetitionGender.Equals("Female") && CompetitionMarker.Equals("Red")) || (!CompetitionGender.Equals("Female") && !CompetitionMarker.Equals("Red"))))
{
IsValid = true;
}
else
{
IsValid = false;
}
return IsValid;
}
depends on what's in CompetitionCourse. You'll have to check that yourself by debugging your code.
You'd be better off making explicitly sure that CompetitionCourse contains null if the ComboBox text field is blank (because I suspect it contains ""):
CompetitionCourse = (string.IsNullOrEmpty(cbCourseRound1.Text)) ? null : cbCourseRound1.Text;
At the moment this is validating regardless of this combobox being
blank or populated.
Check the Items property of the combobox, not the Text Property like.
cbCourseRound1.Items != null && cbCourseRound1.Items.Count > 0
First of all, using .Equals for strings is very Java. C# has operator overloading which looks a lot nicer:
if(CompetitionName!="" && CompetitionGender!="Mixed" ...)
As for the test itself, you'll need to set a break point and see what `CompetitionCourse has. My guess is it's not an empty string, but rather has some spaces in it. Try using
...!CompetitionCourse.Trim()!=""
Your code is diffficult to read, i'll try to simplify it:
private bool Validate(Competition compSetup)
{
bool isValid = cbGenderOfCompetiton.Text != "Female" && cbMarker.Text == "Red";
if (!isValid)
{
isValid = !string.IsNullOrEmpty(compSetup._CompetitionName);
if (isValid)
isValid = compSetup._CompetitionFormatId.Text == "Female";// this is redundant: cbGenderOfCompetiton.Text != "Mixed";
if (isValid)
isValid = CompetitionFormat == 1;
if (isValid)
isValid = cbCourseRound1.SelectedIndex != -1;
if (isValid)
isValid = cbMarker.Text == "Red";
}
return isValid;
}
Note that i've used the SelectedIndex instead of Combobox.Text because it's less error-prone.
Instead of using !Equals, use IsNullOrWhitespace, or IsNullOrEmpty. It works better.
May be you should try to trim the white space around the text box. For example, txtName.Trim();

Best way to check if a drop down list contains a value?

When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?
This is what I've attempted, but it doesn't return a bool.
if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) )
ddlCustomerNumber.SelectedIndex = 0;
There are two methods that come to mind:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new
ListItem(GetCustomerNumberCookie().ToString())))
{
// ... code here
}
or modifying your current strategy:
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != null)
{
// ... code here
}
EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.
That will return an item. Simply change to:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
If 0 is your default value, you can just use a simple assignment:
ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();
This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.
I use this mechanism quite a lot and find it very handy.
What about this:
ListItem match = ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString());
if (match == null)
ddlCustomerNumber.SelectedIndex = 0;
//else
// match.Selected = true; // you'll probably select that cookie value
On C# this works:
if (DDLAlmacen.Items.Count > 0)
{
if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
{
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
}
}
Update:
Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."
So. for this to work on Visual Basic, I had to change the code like this:
If DDLAlmacen.Items.Count > 0 Then
If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
End If
End If
ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}
You could try checking to see if this method returns a null:
if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
//you can use the ? operator instead of if
ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";
If the function return Nothing, you can try this below
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}
Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):
if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Categories