is there a sort of isset() on .NET/C#? - c#

I need to check if there is a param on the uri request.
So I need to check if that param is set. Is there a function on .NET/C#?

An unset value will be null or empty:
value = Request["param"];
if (String.IsNullOrEmpty(value))
{
// param is not set
}
If the param name is in the query string but the value is not, it will be empty. If the name is not in the query string, the value will be null. For example.
&param1=&param2=value
// Request["param1"] is String.Empty
// Request["param3"] is null

Yes, you can use HttpUtility.ParseQueryString() utility method which returns NameValueCollection and then cust call Get():
bool contains = HttpUtility.ParseQueryString(uri.Query)
.Get("ParameterName") != null;
Get() method
Returns A String that contains a comma-separated list of the values associated
with the specified key from the NameValueCollection, if found;
otherwise, null
EDIT:
If you have an instance of the HttpRequest then just use built in indexer like below:
bool contains = Request["ParamName"] != null;

In c# not implemented object is NULL. But if you try to acces to this object you will get the exception. You cat try to catch it or just add # before your variable.
So C# isset looks like this (for array of strings)
// Isset
internal static bool isset(String[] m, int index)
{
return (#m[index] == null) ? false : true;
}
Use it like this: if (App.isset(parts, 1)) cat = parts[1];
Or just "in plase" solution
if (#parts[1] != null) cat = parts[1];
I hope this ansver will help you.

You could use try and catch to wrap your uri request?
catch for NullReferenceException or just exception?

Related

Check if non-valued query string exists in url with C#

I've seen a couple examples of how to check if a query string exists in a url with C#:
www.site.com/index?query=yes
if(Request.QueryString["query"]=="yes")
But how would I check a string without a parameter? I just need to see if it exists.
www.site.com/index?query
if(Request.QueryString["query"] != null) //why is this always null?
I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!
If you do not specify a value, the key will be automatically set to null, so you cannot check its existence.
In order to check if the value actually exists, you can check in the collection of Values equalling null if it contains your Key:
Request.QueryString.GetValues(null).Contains("query")
this is the fastest way to check it thanks to Ludovic's answer
if(Request.QueryString.GetValues(null)?.Contains("query")??false)
It returns null because in that query string it has no value for that key. I think the check you're looking for is this:
if(Request.QueryString.Keys.OfType<string>().Any(k => k == "query"))
or even:
if(Request.QueryString.AllKeys.Any(k => k == "query"))
The latter is probably more appropriate because that array is already cached.
If query was included as a parameter, but no value was specified, then the value of query will be null but it will still exist in Request.QueryString.AllKeys.
If query was not included, it won't exist in Request.QueryString.AllKeys at all.
Ludovic has the right answer. But I would like to offer a more robust version.
var valueEntries = Request.QueryString.GetValues((string)null) ?? new string[] {};
if (valueEntries.Contains("query", StringComparer.OrdinalIgnoreCase))
{
// value is specify in querystring
}
else
{
// value is NOT specify in querystring
}
This is verbose and it works. Here is a .NET Fiddle.
#using System.Linq;
#{
var empties = Request.Url.Query
.Split('&')
.Where(s => !s.Contains("=") || s.Last() == '=');
var keyExistsAndIsEmpty = empties.Any(x => x.Contains("target-key")
}
It turns out that if the value is null, then the key is also null in the QueryString collection. Your best bet is simply to assign a value to the query. There might be a way for you to rename the parameter so that this makes more semantic sense. For example instead of www.site.com/index?getdocument=yes you could do www.site.com/index?action=getdocument
However if you still want the url www.site.com/index?query to work, there is a way: don't use the QueryString at all and parse the URL manually:
string query = Request.RawUrl.Split('?')[1];
if (query == "query")
{
// send the data
}
You cannot use a null check to determine if a key exists when the "=" is not supplied since null means that the key wasn't in the query string.
The problem is that "query" is being treated as a value with a null key and not as a key with a null value.
In this case the key is also null inside Request.QueryString.AllKeys.
I used this generic method to "fix" the null key problem in the query string before using it. This doesn't involve manually parsing the string.
Usage example:
var fixedQueryString = GetFixedQueryString(Request.QueryString);
if (fixedQueryString.AllKeys.Contains("query"))
{
}
The method:
public static NameValueCollection GetFixedQueryString(NameValueCollection originalQueryString)
{
var fixedQueryString = new NameValueCollection();
for (var i = 0; i < originalQueryString.AllKeys.Length; i++)
{
var keyName = originalQueryString.AllKeys[i];
if (keyName != null)
{
fixedQueryString.Add(keyName, originalQueryString[keyName]);
}
else
{
foreach (var keyWithoutValue in originalQueryString[i].Split(','))
{
fixedQueryString.Add(keyWithoutValue, null);
}
}
}
return fixedQueryString;
}
I Prefer to use:
If(Request.QueryString.AllKeys.Contains("query")
{
//
}

Check if an Object has something or not

I have the following property:
IDictionary<string, object> Values { get; }
The property has a few values having one of them the key "culture".
I tried to use that value and casting to a string:
String value = (String)data.Values["culture"] ?? defaultCulture;
This works when the item has some value but when it doesn't I get the error:
Unable to cast object of type 'System.Web.Mvc.UrlParameter' to type 'System.String'.
BTW, System.Web.Mvc.UrlParameter:
http://msdn.microsoft.com/en-us/library/system.web.mvc.urlparameter%28v=vs.108%29.aspx
In the debugger data.Values["culture"] has the value {}. I tested and:
var test_1 = data.Values["culture"] == null; // returns false
var test_2 = data.Values["culture"].ToString() == null; // returns false
How do I check if data.Values["culture"] has something in it or not?
Apparently, you are storing a UrlParameter in that dictionary entry. If you want to get a string out, you will need to use ToString().
The exact expression to use will depend on the type of defaultCulture. If it is a string, then
String value = data.Values["culture"] == null ? defaultCulture : data.Values["culture"].ToString();
if it is a UrlParameter, then
String value = (data.Values["culture"] ?? defaultCulture).ToString();
If you want to get the string if it indeed is a string and a default value otherwise, you can test the type of the valuer using as. Something like:
(data.Values["culture"] as string) ?? defaultCulture
Try this:
String value = (String) (data.Values["culture"] ?? defaultCulture);
The idea is to check for null before trying to cast.
did you use this?
string.IsNullOrWhiteSpace(somestring)

best way to prevent Null failure with string casting

_callReportCode = reader["Call Report Code"].ToString();
I am attempting to handle the possibility for the object I am calling ToString on to be NULL.
I am going to be using the above statement with several variables and I dont want to make an individual try/catch for each one... what is the best way to do null checking for strings.
Other datatypes ive been doing this:
int.TryParse(reader["Account Number"].ToString(), out _accountNumber);
In this code "reader" refers to a SqlDataReader but thats not really important for this question.
Use the null-coalescing operator: ??
callReportCode = (reader["Call Report Code"] ?? "").ToString();
If the data in your field is DBNull.Value (rather than null), this will still work, because DBNull.Value is not null, so the ?? won't be used, and DBNull.Value.ToString() is "", which is what you'd want.
Convert.ToString(reader["Call Report Code"]);
It will return string.Empty if the value is null.
Source: http://msdn.microsoft.com/en-us/library/astxcyeh.aspx
Update: it also works with DBNull, I've just verified.
Update 2: I decided to bring a more complete test here, just to be sure:
DBNull dbNull = null;
DBNull dbNullEmpty = DBNull.Value;
string stringNull = null;
string stringEmpty = string.Empty;
var outcome1 = Convert.ToString(dbNull);//Empty string
var outcome2 = Convert.ToString(dbNullEmpty);//Empty string
var outcome3 = Convert.ToString(stringNull);//NULL
var outcome4 = Convert.ToString(stringEmpty);//Empty string
If your string is nullable, you need to check the value returned from the SqlDataReader against DBNull.Value:
_callReportCode = reader["Call Report Code"] as string;
If the object returned by reader["Call Report Code"] is not a string, it's DBNull.Value, so the as cast is going to set the value of _callReportCode to null as well.
If you must set the string to a non-null in case the database value is missing, add ??, like this:
_callReportCode = (reader["Call Report Code"] as string) ?? string.Empty;
My suggestion is to never convert ToString when the data isn't a string, and if the data is already a string, then calling ToString is redundant, and a cast is all that's required.
I am making an assumption that the datatype in the database is integer, in which case, you can use a nullable int.
int? accountNumber = reader["Account Number"] == DBNull.Value ? null : (int?)reader["Account Number"];
I have made an extension method to do just this thing.
public static class SqlDataReaderExtensions
{
public static T Field<T>(this SqlDataReader reader, string columnName)
{
object obj = reader[columnName];
if (obj == null)
{
throw new IndexOutOfRangeException(
string.Format(
"reader does not contain column: {0}",
columnName
)
);
}
if (obj is DBNull)
{
obj = null;
}
return (T)obj;
}
}
Usage
int? accountType = reader.Field<int?>("Account Number"); // will return NULL or the account number.
The easiest way I have found is
_callReportCode = reader["Call Report Code"] + "";
i have some easiest and common Method.
public static string ToNULLString(this string Values)
{
if (string.IsNullOrEmpty(Values))
{
return "";
}
else
{
return Values.ToString();
}
}
use in C#
string item = null;
string value = item.ToNULLString();
you could create a method that you call when you want to make the check.
This way you have to type the try catch only once...
or you can create an extension method for string class to do this
_callReportCode = Convert.ToString(reader["Call Report Code"]) should ensure there are no null there.
Use following line of code:
_callReportCode = String.IsNullorEmpty(reader["Call Report Code"]) ?
String.Empty :
reader["Call Report Code"].ToString();
instead of the following line:
_callReportCode = reader["Call Report Code"].ToString();
I like using a combination of the null-coalescing operator and the null conditional operator:
string nn = MyObject.myNullableVar?.ToString() ?? "";
it's basically the same as this
string ss = (MyObject.MyNullableVar == null) ? "" : MyObject.MyNullableVar.ToString();
but shorter.
You can perform a check using String.IsNullOrEmpty() to ensure that it isn't going to be null, or you could write an extension method to perform some action if it's not null and another / nothing if it is.

How to i return the value of a property if i dont know the propertyname at run-time?

And let's assume for simplicity that the value of the property needs to always be returned as a string.
public string GetTheValueOfTheProperty(PropertyInfo propertyInfo,Object myObject){
string propname = propertyInfo.Name;
if (propName == "IsSelected"){
return myObject.IsSelected.ToString();
}
//...
}
This works, but it doesn't work if I don't know the name of the property. How would I do that in that scenario ?
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx
You can call propertyInfo.GetValue(myObject, null);.
You can convert to a string with ToString(), but you should check for null values first - otherwise you'll get a NullReferenceException.
The PropertyInfo object lets you invoke the property on the object:
object value = propertyInfo.GetGetMethod().Invoke(myObject, new object[] { });

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

Categories