Getting the Request Variables from an ASP.NET page - asp.net

I wrote the following function that works about 95% of the time, but I need it to work 100% (obviously):
Public Shared Function getPassedVars() As String
Const keyCount As Integer = 54 ' 54 seems to be the number of parameter keys passed by default (for this web_app).
' there are more if there is a form involved (ie. from search page)
Dim oParams As String = ""
Try
With HttpContext.Current
If .Request.Params.AllKeys.Count > keyCount Then
For i As Integer = 0 To (.Request.Params.AllKeys.Count - (keyCount + 1))
oParams &= String.Format("{0}={1}{2}", .Request.Params.Keys.Item(i), .Request.Params(i), IIf(i < .Request.Params.AllKeys.Count - (keyCount + 1), ";", ""))
Next
End If
End With
Return oParams
Catch ex As Exception
Return Nothing
End Try
End Function
It scrubs the Request.Params object for passed variables, which are in the beginning of the array (the remaining ones are ASP parameters). I am pretty sure I've seen a different way to get these parameters, but I haven't been able to figure it out. Any suggestions?
EDIT
So it looks like I can use the Request.URL.Query to achieve this, I will investigate this and post back.
Here is what I came up with:
Public Shared Function getPassedVars() As String
Dim oParams As String = ""
Dim qString As String = ""
Dim oSplit As New List(Of String)
Try
With HttpContext.Current
qString = .Request.Url.Query
If qString.Length > 0 Then 'do we have any passed variables?
If qString.StartsWith("?") Then qString = qString.Remove(0, 1) 'remove leading ? from querystring if it is there
oSplit.AddRange(qString.Split("&"))
For i As Integer = 0 To oSplit.Count - 1
oParams &= String.Format("{0}{1}", oSplit.Item(i), IIf(i < oSplit.Count - 1, ";", ""))
Next
Return oParams
Else
Return Nothing
End If
End With
Catch ex As Exception
Return Nothing
End Try
End Function
So far so good.

Request.QueryString is a NameValueCollection, so the easiest way to get the "parameters" is to do the following:
foreach (String s in Request.QueryString) {
Response.Write(s + " = " + Request.QueryString[s]);
}
Where is your function located? If it's executing in the page's code behind then you definitely do not need to use the HttpContext variable.

It looks like you are trying to get values from the query string.
For example, for this URL:-
http://www.tempuri.org/mypage.aspx?param1=x&param2=y
I assume you want retreive the values of the query string parameters param1 and param2?
If so, just use:-
Dim param1 as String = Request.QueryString("param1")
Otherwise, if these parameters are contained in a form (an HTTP POST request) then use the method which Mitchel Sellers suggests.

If you know the name you can use the following to get it by key value
Dim myParamValue as String = Request.Form("MyKeyName")
Otherwise, you can loop through the form collection, by key etc, to get the values. The key is, do you really need to be parsing all 54 items? Or are you simply looking for a few specific values?

httpcontext.Current.Request.QueryString("KeyName")

Request.Params will contain the query parameters you're after.
There's no need to parse the info from Request.URL since it's already done for you.

Related

How to get my params value with a & in the URL?

www.myurl.com?param1=123&param2=456 OK
www.myurl.com?param1=123&param2=456 NOT OK
In my vb code behind, with the second URL, I get the value of param1 only.
Me.Page.Request("param1") : value OK
Me.Page.Request("param2") : value 0
Firstly, I would advise rethinking how your URL is built with a view to removing the need for an & it will be far easier for you.
If this is not possible for whatever reason, you will need to extract the parameter values from the querystring yourself.
One possible solution:
Dim url As String = Request.RawUrl
Dim urlParams As String() = url.Split("?"C)
If urlParams.Length > 1 Then
Dim parameters As String() = urlParams(1).Split(New String() {"&"}, StringSplitOptions.None)
For Each param As var In parameters
' will give you the paramater value
Dim value As String = param.Split("="C)(1)
Next
End If

How does one set a property of a JsonObject dynamically?

I am using a method of passing Json to and from my markup using jquery and ajax. This can be described in more detail on this page: http://blogs.telerik.com/aspnet-ajax/posts/12-04-27/the-present-and-future-of-using-json-in-webforms.aspx
In this snippet of code, I try to set the object's value dynamically by setting a string variable named "test" to a business object's value:
Dim objOrder As Object = New JsonObject()
For Each Order As BoVendorOrder In Orders
Dim Vendor As New BoVendor(Order.VendorID)
Dim test As String = Order.VendorOrderID
objOrder.test = Vendor.VendorName + " - " + Order.VendorOrderPoNumber
Next
I left out some code for the sake of brevity. The goal is to get the objOrder.test to be equal to the VendorOrderID (a number in our SQL database) so that the JSON looks like this:
{
"123456": "VendorName - PONumber",
"678901": "VendorName - PONumber"
}
Any of you guys out there know how to do this?
Do you really need the order IDs to be properties of the object? It might be easier to just return a serialized Dictionary(Of String, String). You could still look up by order ID and it would be easier to loop over than the props of the Javascript object.
Here's an example of what you'd need to do using the dictionary approach:
Dim OrdersDict as New Dictionary(Of String, String)()
For Each Order as BoVendorOrder In Orders
If Not OrdersDict.ContainsKey(Order.VendorOrderID) Then
OrdersDict.Add(Order.VendorOrderID, Vendor.VendorName + " - " + Order.VendorOrderPoNumber)
End If
Next
' Serialize the dictionary object to JSON
' Using System.Web.Script.Serialization.JavascriptSerializer:
Dim Serializer As New JavaScriptSerializer
If MaxLength Then Serializer.MaxJsonLength = Int32.MaxValue
Dim x as String = Serializer.Serialize(OrdersDict) 'Return or response.write x as needed
'or
'Using JSON.net
Dim x as String = JsonConvert.SerializeObject(OrdersDict) 'Return or response.write x as needed

Ignoring specific query string parameters in custom sitemapprovider

I’ve written my own staticsitemapprovider which builds a dynamic site map. The problem I have is that sometimes pages will have additional parameters in the query string which I need to ignore.
Public Overrides Function FindSiteMapNode(ByVal rawUrl As String) As SiteMapNode
Dim startpos As Integer = 0
Dim endpos As Integer = 0
If rawUrl.Contains("pagetype=") Then
startpos = rawUrl.IndexOf("pagetype=")
endpos = rawUrl.IndexOf("&", startpos) + 1
If endpos >= startpos Then
'not the last param
rawUrl = rawUrl.Remove(startpos, endpos - startpos)
Else
'must be the last param
rawUrl = rawUrl.Remove(startpos)
End If
End If
Return MyBase.FindSiteMapNode(rawUrl)
End Function
I've also overridden the FindSiteMapNode function that takes in a HttpContect object. With this I simple find the URL of that request and run it though the same function above.
However with this my sitemappath (which is bound to the site map) returns nothing on every page.
In the end this turned out to be a very simple fix. All i needed to do was check to see if the the parameter was the first in the url. If it wasn't, I aslo needed to remove the ampersand - so it would be startpos - 1
Cheers

Getting values from any URL

I have this url : http://localhost:49500/Learning/Chapitre.aspx?id=2
How can I get just the value of id in this url ?
You can access all the query strings through the Request.QueryString() array:
Request.QueryString("id") will give you the 2
Despite my own comment saying it has been answered, here is the code.
Dim idval As String = System.Web.HttpUtility.ParseQueryString("http://localhost:49500/Learning/Chapitre.aspx?id=2")("id")
Create a new instance of System.Uri class with the URL and the use the Query property to get the query string part.
Once you have that string, do String.Split on the '&' character. For each string in the resulting array, do String.Split on the '=' char. In the resulting array, the first string is the query parameter name, the second is the value (if present). Check if the name is the one you are interested in and if it is, get the value.
Update: Boy, I haven't touched VB since 1999... :-)
Here's the code for my answer. I didn't realize that the Url you want to parse is the page Url. For that specific case, Request.QueryString("id") will indeed be a better solution.
Dim url As Uri = New Uri("http://localhost:49500/Learning/Chapitre.aspx?id=2")
Dim query As String = url.Query.Trim("?")
Dim parameters() As String = query.Split("&")
Dim tokens() As String
Dim value As String = ""
For index As Integer = 0 To parameters.Length - 1
tokens = parameters(index).Split("=")
If tokens(0).ToLower = "id" Then
If tokens.Length = 2 Then
value = tokens(1)
End If
Exit For
End If
Next
' At this point value contains the parameter value or
' is empty if the parameter has no value or if the parameter is not present
You can use Request vb method
Using the url : http://localhost:49500/Learning/Chapitre.aspx?id=2
Dim valueId = Request("id")
to test the code:
response.Write(valueId)
value Id is 2

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

Resources