I want to know the difference between the following.
Difference between Session("foo") is "test" and Cstr(Session("foo")) = "test"
I understand the second one is casting to string. The thing I don't get is, one one page, when I tried,
if Session("foo") is "test" Then
Do something
This worked on one page. On some pages the do something does not get executed even if Session("foo") is "test". On the other hand Cstr(Session("foo")) = "test" always works. Why is the difference. Out of the two, which suits better for convention?
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False. Ref
So in your case you need to convert the object of the Session to string before you want to compare it with another string value type.
To Answer to your next question
You can set a property in your page instead of repeating that code several times on your page like below:
Public Property MyValue() As String
Get
Return Session("MyValue").ToString()
End Get
Set
Session("MyValue") = value
End Set
End Property
Now you can Set and Get this value anywhere inside your page, like this:
MyValue = "This is my value" 'set a value
Dim message As String = MyValue 'get a value
The return type of Session is Object.
The Is operator compares the object references of two objects.
The = operator compares the values stored in two objects.
Since you want to check to see if the session has a particular name, you want to compare the values of two strings, you need to use the = operator.
When you use the Is operator to compare object references, it checks to see of the two references are pointing to the same string instance. But, Is will evaluate to false if you compare two separate object instances, even if both instances contain the same string value.
Related
Is it possible to add multiple values in one session variable ?
In my login page , one session variable is carrying a value, i need to append some other data in same session variable in another page.
In Login.Aspx.Vb
Session.Add("UserKey", "DATA_1_PAGE1 ")
In Dashboard.Aspx.Vb
Session.Add("UserKey", "| DATA_2_PAGE2")
In Process.Aspx.vb
Dim Session_StateValue = HttpContext.Current.Session("UserKey")
In Session_StateValue , I want my values as 'DATA_1_PAGE1| DATA_2_PAGE2'.
Is there any mechanism to append in session variable other than assign to a string and append along with the assigned string once again .
Please advice.
Dealing with strings, you can use List's, Dictionaries, Arrays, String etc.
Simplest way to concatenate string values would likely be
Session.Add("UserKey", "DATA_1_PAGE1")
Session.Add("UserKey", Session("UserKey").ToString() & "| DATA_2_PAGE2")
Dim str As String = Session("UserKey").ToString()
Another way could be using a List(Of String)
Session.Add("key", New List(Of String) From {"string1"})
DirectCast(Session("key"), List(Of String)).Add("string2")
Dim str As String = String.Join("|", DirectCast(Session("key"), List(Of String)).ToArray)
Now, based on how your are going to use it, persistence, serialization, etc., one might be more appropriate than the other.
You can store more than just strings in Session, like DateTime or some Person object that you defined yourself - how would you have the system implement an "append" then that is valid for all sorts of (combinations of) values?
So the only way is to get the original value as string, append the new value yourself and put that combination in Session.
But make sure then when a user happens to submit that second page twice (the user will always find a way...) you don't append that value twice. Maybe it's better to keep it in separate Session values and only combine them when you need the combined value.
I have a Guid loaded with a ID that a user selected from a GridView.
I want to pass this Guid to another page, but i dont know how to append it to the statement below:
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
Here is the full code:
Dim dvrLicense As GridViewRow
Dim guidLicense As Guid
dvrLicense = grdAllUserLicense.SelectedRow
guidLicense = StringToGUID(dvrLicense.Cells(1).Text.ToString)
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
the variable i want to pass is called: guidLicense.
Use a format string:
Response.Redirect(String.Format("LicenseDetailsView.aspx?idLicense={0}", guidLicense))
Or perhaps just concatenate it (though the former is preferred):
Response.Redirect("LicenseDetailsView.aspx?idLicense=" & guidLicense)
The point being that there has to be some operation performed on the two values (the string literal and the variable). Putting them next to each other doesn't mean anything to the compiler. A method call with the values as arguments, or an operator between the values, will instruct the code to do something with those values.
I have a class type object, such as:
Private Class Car
Public Property Make As String
Public Property Model As String
Public Property Used As Boolean?
Public Property Mileage As Integer?
Public Property DateSold As Date?
End Class
I'm parsing a query string that's posted to my page that may or may not have key/value pairs for the above properties. For example, it may just be:
?Make=Toyota
I have a table in SQL Server based on the Public Properties you see above, and I'm allowing NULLS on all columns. (My real data has more fields, so this is for explanation purposes)
CREATE PROCEDURE InsertCar
#Make varchar(25),
#Model varchar(25),
etc.
I'm not setting default values in the parameters in the stored procedure above. I want to know of a cleaner way to do this from code.
For example:
The data is posted to my page... I use httputility to parse it, and I can build a new object, such as:
Dim record As New Car
record.Make = Data("make")
record.Model = Data("model")
record.Used = Data("used")
record.Mileage = Data("mileage")
record.DateSold = Data("datesold")
Afterwards, I build some parameters for my stored procedure, but here's where I think I can improve:
Dim pars As New List(Of SqlParameter)
pars.Add(New SqlParameter("#Make", If(record.Make = Nothing, DBNull.Value, record.Make))
and so on...
So you can see my ternary operators for building the parameters. Is there a cleaner way, perhaps using default values or when the class is being put together to make this cleaner?
This is more of a precision and best practice question I think. Should I be assigning DBNull.Value to the public properties? Or is how I'm doing it sufficient? Is there a cleaner way to map nullable properties?
My values from the query string are parsed into a NameValueCollection, so is there an easier way to just iterate over the ones that exist, and if not exist in the class, automatically build the parameter with DBNull.Value?
I hope my question makes sense. With a lot of data it just seems ugly with all the if/then DBNull.value, etc. I feel like I could be saving myself a step somewhere along the way. The class object is helpful for organization and is utilized in other parts of the code, or else I'd probably just build the parameters and be done with it.
You can set default values in the stored procedure parameters.
CREATE PROCEDURE InsertCar
#Make varchar(25) = null,
#Model varchar(25) = null
...
And just pass your object, if it is null/missing the stored proc will default the missing paramater value to null
pars.Add(New SqlParameter("#Make", record.Make))
The SQL table also needs to accept nulls.
Or, use the vb.net IF() operator with 2 parameters
pars.Add(New SqlParameter("#Make", If(record.Make,DBNull.Value))
Is there a VB.NET equivalent for C#'s '??' operator?
I am writing a code that calls a column from a dataset using a SQL query. I use two parameters to identify which rows to select. One is the ProductSerialNumber, and the other is a datetimestamp. See my SQL query below
Select TestStation FROM tblData
WHERE ProductSerialNumber = ? AND Datetimestamp = ?
In the dataset's datatable the productserialnumber is formatted as text, and the other is formatted as a date (as you would expect).
In my vb.net code, I grab the Datetimestamp from another source (don't ask why, the only thing you need to know is that it grabs a valid datetimestamp, dimensioned as a date, that matches exactly with the tblData's entry) and I use the premade query to generate a datatable. The query is a Fill query called "TestStationLookUp"
my vb.net code looks like this
Dim dt as new dataset.tbldataDataTable
Dim dta As New DataSetTableAdapters.tbldataTableAdapter
Dim ProductSerialNumber as string = "XXXXXX"
Dim DateTimeStamp as date = SomeDateVariable
dta.TestStationLookUp(dt, ProductSerialNumber, DateTimeStamp)
It is here that the code tells me:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Line 7366: dataTable.Clear
Line 7367: End If
Error: Line 7368: Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Line 7369: Return returnValue
Line 7370: End Function
I cannot understand why this error arises, as everything is dimensioned the way it should be. This exact code setup works elsewhere in my code (except it doesn't use a date), but this specific piece won't work.
Also, if I go to the dataset in my solution, I can use the "preview data" on this query and type in the EXACT same parameters (the ProductSerialNumber and DateTimeStamp that match the record in the table AND what I use in my vb code) and it will give me produce the table I want.
Can anyone assist?
This error means that you are trying to access not valid unique id "ProductSerialNumber", maybe it does not exist
Failed to enable constraints. One or more rows contain values
violating non-null, unique, or foreign-key constraints.
Instead of passing the variable that comes from dataset ,pass a valid number that you are sure it exists in database
The Problem
What is the proper way to check for the foo parameter in the following url's querystring using asp.net? Is this even possible?
http://example.com?bar=3&foo
I have tried checking Request["foo"] as well as Request.QueryString["foo"] and I get null for both. I have also tried populating a List with the values from the QueryString collection but as I mention below, it does not include the value.
The Question
I understand that there is no value, but shouldn't Request["foo"] return an empty string rather than null? Is there a way to find out if a querystring key exists even if it has no value?
Notes
I found here that Request.QueryString.AllKeys includes null for blank querystring parameters.
[edit]
As stated below by James and Dreas a Regex to parse the raw url might be the best (and possibly only) approach.
Regex.IsMatch(Request.RawUrl, "[?&]thumb([&=]|$)")
You can use null as the key for the NameValueCollection and it will give you a comma-delimited list of parameter names that don't have values.
For http://example.com?bar=3&foo you would use Request.QueryString[null] and it would retrieve foo.
If you have more than one parameter name without a value, it will give you a value that is comma-delimited.
For http://example.com?bar=3&foo&test you would get foo,test as a value back.
Update:
You can actually use Request.QueryString.GetValues(null) to get the parameter names that don't have values.
Request.ServerVariables["QUERY_STRING"] will return the query string, complete, as a string. Then search it using a Regex or IndexOf
You get null because the foo parameter doesn't have a value with it.
...What's the problem exactly?
If you still want to check for its existence (although it lacks a value), try something like this:
bool doesFooExist = Request.Url.AbsoluteUri.IndexOf("foo=") >= 0 ? true : false;
Dreas is correct. Variable "bar" has a value but foo does not.
QueryString["Bar"] will return 3 because it has the value 3 associated with the variable Bar. However, Foo will return null because their is no value and when you are calling QueryString on a variable or key, you are querying for the value, not the key, so that is why you are returning null.
query string is probably a waste one. If you use Request.Params[""] or iterate it, then you will find your desired one. Its really handy than other things.
Let me know if you need any help in this.