Passing a Guid through to another page ASP.NET - asp.net

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.

Related

Can we add multiple values to the same session variable in ASP.net

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.

Difference between Session("foo") is "test" and Cstr(Session("foo") = "test"

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.

Using Date parameter in SQL query, ASP.net

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

how to add records from DataTable to ArrayList using AddRange Method

Hey guys,
i have a dataTable, which contains a column which has 100 rows, now i want to add those rows in ArrayList, but not with the Add Method, because i have to use for loop for adding records one by one, so i want to prefer addrange method of arraylist, so it is possible to add records in arraylist from DataTable using AddRange.
Below is the code which i am using.
Dim adapGetImages As New SqlDataAdapter("select distinct FileName from Files where Filename<>'' and (RIGHT(FileName,3) = 'gif' or RIGHT(FileName,3) = 'jpg' or RIGHT(FileName,3) = 'bmp') order by FileName", connection)
Dim dtGetImages As New DataTable()
adapGetImages.Fill(dtGetImages)
ArrayList1.AddRange(dtGetImages.Rows[0][0].ToString())
The last line is where i am stuck. as if i run this it will just add single row, and if i say dtGetImages.Rows.ToString() then this will just Add System.DataRow in Arraylist and not its content.
Please reply what could be done for resolving this issue without any loops.
Thanks in Advance.
Something like this should work:
ArrayList1.AddRange(dtGetImages.Rows.Cast(Of DataRow)().[Select](Function(r) r(0).ToString()).ToArray())
Update
There are a few concepts at work here. First of all, you're not trying to add the rows to the list, but rather the first value in each row. As you mentioned, you could use a for loop to get this value out of each row and add it to a list, but loops like that aren't very concise or declarative. This is why we have LINQ (Language-Integrated Queries): a framework that simplifies the transformation of collections of values.
The Select method is an extension method defined in the LINQ framework. It takes as an argument a function that defines what transformation to perform on each item in the given collection. When the result of the Select is invoked, the given function is performed on each value, producing a new collection based on the results. Here we give it the function:
Function(r) r(0).ToString()
..., which tells it:
Given a variable r, get the zeroth index of r and call ToString() on the result.
So if this Select method is called on an IEnumerable<DataRow>, the resulting collection will be an IEnumerable<string>. Since the ArrayList.AddRange method requires an ICollection, we have to change our IEnumerable<string> into something that implements ICollection. As it turns out, arrays implement ICollection, so we can use the ToArray() method from LINQ to convert it into a value that ArrayList.AddRange will accept.
There's just one problem: the DataTable class was written before generics were part of the .NET framework, so the DataRowCollection class implements the non-generic IEnumerable interface rather than the strongly-typed IEnumerable<DataRow>. Since our Select method needs to start with an IEnumerable<DataRow>, we have to do something to convert dtGetImages.Rows into a IEnumerable<DataRow>. The Cast method, also provided by LINQ, will do this for us. We tell Cast that we happen to know that everything in the given IEnumerable (the DataRowCollection in this case) is going to be a DataRow, so it can safely cast each item into a DataRow, leaving us with the IEnumerable<DataRow> that we need to use the Select method on.
Hopefully that explains things pretty well. One thing you should be aware of is that this doesn't eliminate the use of loops. When you call .ToArray(), it pulls items from the .Select, which pulls items from the .Cast, which iterates over dtGetImages.Rows the same as if you'd written a for loop to populate an array. The only difference is that LINQ makes your code more declarative. It's the difference between saying:
For each DataRow in the Rows property of this DataTable, I'm going to create a variable called row. Then I will call ToString on the zeroth element of this variable and add the result to the ArrayList.
... and saying:
I am calling ToString on the zeroth element out of each DataRow in the Rows property of this DataTable, and adding the results to the ArrayList.
They both mean roughly the same thing, but one is both clearer and more concise.
The MSDN page for the Fill method has this note:
When handling batch SQL statements that return multiple results, the implementation of Fill and FillSchema for a .NET Framework data provider retrieves schema information for only the first result.
Are you getting the schema information for the first result?

Converting Decimal In a Label to an Integer

Currently using VS2008, VB.NET, SQL.
I have a FormView from a Data Source that is getting some fields that are stored as Decimals in the SQL Database.
I am grabbing the field from the FormView as such:
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
I need to take this value, and convert it to an Integer, then send it along to an API. I have the API Calls done, tested and working, but I'm getting an error as when it is getting this value, the API is returning "Must be an Integer" error.
What I have tried so far:
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
Dim AvgTicket1 As Integer
AvgTicket1 = Double.Parse(AvgTicket.Text)
Do something with AvgTicket1
I have also attempted to Round the Value, then convert it and call it - no luck.
Checking the value of AvgTicket1 (Writing it out to a Label or Response.Write) shows "100", where the database value was 100.00. But the API is still getting 100.00, apparently. Any other conversion method that I've attempted states errors that the Label cannot be converted to Integer.
What are some methods I can successfully convert this value to an integer from a label?
The title of your question and the text of your question point to two different things.
Assuming you want to know how to safely convert the decimal value retrieved from the database, which is presumably the value of AvgTicketL, before calling your API you would do the following:
Create a variable of datatype Integer and use System.Int32.TryParse() to safely convert the decimal to an integer. Then pass that variable. (Code coming)
Dim testInt as Integer = -1
If System.Int32.TryParse(AvgTicketL.Text, testInt) Then
' Do something with testInt - call the API using the value
Else
' code to execute if the parse fails.
' This could be whatever you need the code to do if the value of AvgTicketL.Text can't be properly parsed into an Int value.
End If
After some fooling around this is what I was able to do to get this to work...
I took some of what David had said, and then just made a simple adjustment - I don't know why I hadn't thought of it earlier!
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
Dim AvgTicketI As Integer = "-1"
I dimmed a second variable as an int, then
AvgTicketI = CInt(AvgTicketL.Text)
From there, I just called AvgTicketI as the variable to pass to the API. Worked!
Thanks, David, for the guidance!

Resources