Within the context of an ASP.NET page, I can use Request.QueryString to get a collection of the key/value pairs in the query string portion of the URI.
For example, if I load my page using http://local/Default.aspx?test=value, then I can call the following code:
//http://local/Default.aspx?test=value
protected void Page_Load(object sender, EventArgs e)
{
string value = Request.QueryString["test"]; // == "value"
}
Ideally what I want to do is check to see if test exists at all, so I can call the page using http://local/Default.aspx?test and get a boolean telling me whether test exists in the query string. Something like this:
//http://local/Default.aspx?test
protected void Page_Load(object sender, EventArgs e)
{
bool testExists = Request.QueryString.HasKey("test"); // == True
}
So ideally what I want is a boolean value that tell me whether the test variable is present in the string or not.
I suppose I could just use regex to check the string, but I was curious if anybody had a more elegant solution.
I've tried the following:
//http://local/Default.aspx?test
Request.QueryString.AllKeys.Contains("test"); // == False (Should be true)
Request.QueryString.Keys[0]; // == null (Should be "test")
Request.QueryString.GetKey(0); // == null (Should be "test")
This behavior is different than PHP, for example, where I can just use
$testExists = isset($_REQUEST['test']); // == True
Request.QueryString.GetValues(null) will get a list of keys with no values
Request.QueryString.GetValues(null).Contains("test") will return true
I wrote an extension method to solve this task:
public static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.AllKeys.Contains(key))
return true;
// ReSharper disable once AssignNullToNotNullAttribute
var keysWithoutValues = collection.GetValues(null);
return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
Request.QueryString is a NameValueCollection, but items are only added to it if the query string is in the usual [name=value]* format. If not, it is empty.
If your QueryString was of the form ?test=value, then Request.QueryString.AllKeys.Contains("test") would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query.
I use this.
if (Request.Params["test"] != null)
{
//Is Set
}
else if(Request.QueryString.GetValues(null) != null &&
Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
//Not set
}
else
{
//Does not exist
}
TRY this one, it solved my issue!
It will count either the query string has a value or empty and then you can check the required query string value with the Key.
if (!Page.IsPostBack)
{
if (Request.QueryString.Count > 0)
{
if (Request.QueryString["departmentId"] != null)
{
GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
rbListEmpsSurvey.Items[1].Selected = true;
}
else if (Request.QueryString["SurveyStatus"] != null)
{
SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
GetSurveyByDeptAndStatus(status: SatisfactionStatus);
GetDepartments();
}}}
Request.QueryString.ToString().Contains("test")
This works in the special case where you're looking for a single querystring parameter, e.g. MyFile.aspx?test
For more complex, general, cases then other solutions would be better.
Related
I have a method that returns an ItemCollection, I want to stop the function early if there is no information provided. I would normally do this with a return; however as my method expects an ItemCollection it fails. I have this as a work around but it seems frankly hacky. Is there something I am missing. I tried just return; and I would prefer not throw an exception.
private ItemCollection loadLeft_Click(object sender, RoutedEventArgs e)
{
var leftUser = UsrLeft.Text;
if (leftUser == "")
{
MessageBox.Show("No User Entered");
GroupListLeft.Items.Add("");
var fail = GroupListLeft.Items;
return fail;
}
//Succesful test do stuff
var leftItems = GroupListLeft.Items;
return leftItems;
}
You have few options:
throw a new Exception (maybe even a custom one like NoUserEnteredException("someText")).
return null
return an empty collection or dummy object (see Null-object pattern)
The last one is better choice, in this case you don't need write a null-check or a try-catch section in client code.
You will need to return something that equates to an ItemCollection, depending on how you may want the calling procedures to handle such a return you could use a null return:
if (leftUser == "")
{
MessageBox.Show("No User Entered");
return null;
}
Or return a new ItemCollection e.g.
if (leftUser == "")
{
MessageBox.Show("No User Entered");
return new ItemCollection();
}
You will need to return null, like
private ItemCollection loadLeft_Click(object sender, RoutedEventArgs e)
{
var leftUser = UsrLeft.Text;
if (leftUser == "")
{
MessageBox.Show("No User Entered");
return null;
}
//Succesful test do stuff
var leftItems = GroupListLeft.Items;
return leftItems;
}
You can use "return null" which I do from time to time, but its not a good coding convention. Another option is to throw an exception and then catch it. Both is bad coding conventions and makes the code that uses this button add some rather obscure logic and dependencies.
From studying SOLID principles I would argue a better solution is to make a new type of object to return. f.ex. one that holds a list, but also a status message and then make it react a bit like when you have an HTTP request that depends on a success and otherwise cannot expect to have any content. This way, the object makes it clearer what to expect.
A fourth option, since this sounds UI related, is to possible have the click callback somehow and either update the collection, or update with an error message directly. But this might also be a bad coding convention that has impractical dependencies in the code.
Your code seems to return an object when you click on something.
(I am no expert in WPF, i don't know if this is possible).
I would encapsulate the function that returns the ItemCollection in a separate function and check whether the User is valid BEFORE calling this function.
This way you ensure that the ItemCollection is always valid (because you don't even try to retrieve it with an invalid user). Something like this:
private void loadLeft_Click(object sender, RoutedEventArgs e) {
var leftUser = UsrLeft.Text;
if(leftUser != "") {
ItemCollection coll = getItemCollectionForUser(leftUser);
}else {
//Error Handling
}
}
private ItemCollection getItemCollectionForUser(string user) {
//return ItemCollection here
}
Note how I wrote a separate function that returns the ItemCollection and the Click function returns nothing.
It's such that I have a method that I call 7 times and I would like the code to be made nicer and at the same time easy to read and understand.
How can I hold it somewhere?
Just pt, I'll do like this.
#if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == true)
{
#Html.Raw("col-md-8");
}
else if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == false)
{
#Html.Raw("col-md-12");
}
Basically, I think that you could do this here but it does not work in any way.
Note that I do it for example on the index.cshtml page.
As far I Understand, You call HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) this function many times from the view; Now you want to store the result in any variable then use the variable all the places.
If it is then try this:
#{
var variableName = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
}
#if(variableName == true)
{
// do your stuff
}
else if(variableName == false)
{
// do your stuff
}
Just store the value in a variable. In this example I use a variable named flag.
#var flag = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
#if (flag)
{
#Html.Raw("col-md-8");
}
else
{
#Html.Raw("col-md-12");
}
I have a click event handler which has to check if two text boxes are null or not, if both aren't the values are given to two variables and passed to another method.
One variable is a String, the other an integer. If the String is null but the integer isn't, it will work fine(Which it shouldn't!). But, if the integer is null and the String isn't, it will give me an error which is expected because it should not have reached that point.
Here's the code:
private void btnInsert_Click(object sender, EventArgs e)
{
String ActorName;
int Position;
if ((txtPosition.Text != null))
{
if ((txtActorName.Text != null))
{
ActorName = txtActorName.Text;
Position = int.Parse(txtPosition.Text);
InsertIntoArrayList(ActorName, Position);
PopulateActors();
}
else
{
MessageBox.Show("Please enter an Actor Name");
return;
}
}
else
{
MessageBox.Show("Please enter a position");
return;
}
}
As you can see, if txtPosition is not null, it then tests txtActorName. If either are null, it throws the relevant message. Assuming both are not null, it assigns the values to the variables and passes these to the InsertIntoArrayLIst method, followed by a call to the PopulateActors method.
If I enter an Actor name and a position, everything works fine. It's only if I don't enter a position that it somehow misses the fact that nothings entered, then slips up at the line Position = int.Parse(txtPosition.Text); because txtPosition is null.
Any help would be greatly appreciated!
Try using e.g. !string.IsNullOrEmpty(txtPosition.Text) instead of txtPosition.Text != null.
Alternatively, just use txtPosition.Text != "". After all, the Text property should never actually be null.
And of course, you should apply the same fix to both values, txtPosition and txtActor.
Don't confuse null and empty strings. They aren't the same thing.
The Text property of any control will only ever be null if you explicitly set it to null. In most cases you don't need to check this at all for that property; just comparing to an empty string is good enough
The String.IsNullOrEmpty() and String.IsNullOrWhitespace() methods are your friends.
There's no reason to nest the If blocks. Just use guard clauses to check one followed by the other for cleaner code:
.
private void btnInsert_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhitespace(txtPosition.Text))
{
MessageBox.Show("Please enter a position");
return;
}
if (string.IsNullOrWhitespace(txtActorName.Text))
{
MessageBox.Show("Please enter an Actor Name");
return;
}
int Position;
if (!int.TryParse(txtPosition.Text, out Position))
{
MessageBox.Show("Please enter a number in the position field");
return;
}
InsertIntoArrayList(txtActorName.Text, Position);
PopulateActors();
}
You could also use if (!string.IsNullOrWhiteSpace(txtPosition.Text) if you want to check for white spaces as well. Although performance wise it is a bit slower then using the standard string.IsNullOrEmtpy
if (txtPosition.Text != string.Empty) is another way to check.
Try This, it may resolve your Problem
ActorName = txtActorName.Text;
Position = int.Parse(txtPosition.Text=="" ? "0" : txtPosition.Text);
I have a strange problem I'm checking in my code behind the user if he is active or not with as simple if .. in my Page_Load method as you can see here
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
this.getParameters();
if (!this.IsPostBack)
{
if (paramTR.ZevUser.Active == 0)
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
}
But when I make a go throw to this method I get allays nullreferenceexception why so ever .. but the private ZevUser variable is not null it's full..
I really don't have a clue why is this happing, it would be really cool if someone could explain me this why this is happening
Thanks for help and fast answer
You need to break your code down so you can debug it easier or add logging if you cannot debug this code locally.
Remember that when debugging something, the worse mistake you can make is to make assumptions. Start from the beginning and follow the process through. Don't assume that the problem is something and don't assume that the problem can't be something:
I've included a broken down, more readable version below. You can now add logging around this or easily add breakpoints:
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
this.getParameters();
if (!this.IsPostBack)
{
if ((this.paramTR != null) &&
(this.paramTR.ZevUser != null) &&
(this.paramTR.ZevUser.Active == 0))
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
string sessionId = Session["SessionId"] as string;
if (sessionId != null)
{
int session = int32.Parse(sessionId);
ZevUser user = ZevUser.GetById(session);
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
}
}
Why are you passing the session id to ZevUser.GetById()? I would expect this to take a user id, or for the method to be called something like ZevUser.GetBySessionId(). At the moment it's quite confusing.
This line is causing the issue:
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
This is because Session["SessionId"] can be null, and is null in this case.
If you are looking to get the SessionId that is set by ASP.net, then use this.Session.SessionID (source).
If you are storing a value in Session["SessionId"] that you are trying to retrieve, then do a null-check first:
if (Session["SessionId"] != null) { ...
You should consider testing the SessionId variable before using it by doing something like that :
if (!string.IsNullOrEmpty(Session["SessionId"].ToString()))
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
The best way to debug your exception is to enable debug when the exception is thrown.
For this, go to Debug>>Exceptions
and then enable first four checkboxes (maybe) and then try debugging the project. You will be halted at the position from where the exception will be thrown.
I'm implementing backword function on a button. that when clicked moves to the previous link in the stack. the problem is this if it has one element in the stack pop() it gives an error of stack empty.
private void Backward_Click(object sender, EventArgs e)
{
try
{
if (simpleStack.Count != 0)
{
simpleStack.Pop();
string open = simpleStack.Pop();
PopulateListView(open);
complicatedStack.Push(open);
}
else if (simpleStack.Count == 0)
{
Backward.Enabled = false;
}
It works when I have more than one clicks n goes back to the previous item selected.but does not show the last one. I'm passing string in simpleStack. can anybody tell me what I'm missing?
Look at your code:
simpleStack.Pop();
string open = simpleStack.Pop();
You're popping twice, and ignoring the first result. Why would you do that? I suspect you can just remove the first Pop call.
Also note that your else clause doesn't need to check simpleStack.Count == 0 - it must be, otherwise you wouldn't be evaluating the else clause. (Unless you've got multiple threads doing stuff of course - which wouldn't be a good idea.)
Try this -
private void Backward_Click(object sender, EventArgs e)
{
try
{
if (simpleStack.Count != 0)
{
//simpleStack.Pop(); // Remove this line
string open = simpleStack.Pop();
PopulateListView(open);
complicatedStack.Push(open);
}
else if (simpleStack.Count == 0)
{
Backward.Enabled = false;
}
}
}