Getting values from any URL - asp.net

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

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

Visual basic and Json.net Web request

Basically what im trying to do is make a program that list game information for league of legends.. using there API to extract data. how this works is you Search there username and it returns an integer linked to that account, you then use that integer to search for all of the information for that account, EG account level, wins, losses, etc.
I've run into a problem i can't seem to figure out.. Please not that I'm very new to Json.net so have little experience about working with it.. Below is how the search for the user ID is found, The First section is the Username Minus Any spaces in the name the next is the ID which is the information i require.
{"chucknoland":{"id":273746,"name":"Chuck Noland","profileIconId":662,"summonerLevel":30,"revisionDate":1434821021000}}
I must be declaring the variables wrong in order to obtain the data as everything i do it returns as 0.
these are the following class i have to store the ID within
Public Class ID
Public Shared id As Integer
Public Shared name As String
End Class
Looking at a previous example seen here Simple working Example of json.net in VB.net
They where able to resolve there issue by making a container class with everything inside it.. My problem is that The data i seek i always changing.. The first set will always be different to the "Chucknoland" that's displayed in the example.. is someone able to explain how i could go about extracting this information?
Please note that the variables rRegion has the value of what server there on, Chuck Noland is on OCE, and sSearch is the Username.. Due to Problems with API keys i had to remove the API key from the code... But the URL returns the Json Provided.
'URL string used to grab Summoner ID
jUrlData = "https://oce.api.pvp.net/api/lol/" + rRegion + "/v1.4/summoner/by-name/" + sSearch +
' Create a request for URL Data.
Dim jsonRequest As WebRequest = WebRequest.Create(jUrlData)
'request a response from the webpage
Dim jsonResponse As HttpWebResponse = CType(jsonRequest.GetResponse(), HttpWebResponse)
'Get Data from requested URL
Dim jsonStream As Stream = jsonResponse.GetResponseStream()
'Read Steam for easy access
Dim jsonReader As New StreamReader(jsonStream)
'Read Content
Dim jsonResponseURL As String = jsonReader.ReadToEnd()
jUrlString = jsonResponseURL
this is the request i have to obtain the information, and this is the code i tried to use to display the ID for that json.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim obj As ID
obj = JsonConvert.DeserializeObject(Of ID)(jUrlString)
MsgBox(obj.id)
End Sub
Is anyone able to explain how i can go about getting this to work?
One way to handle this would be to get the item into a Dictionary where the keys are the property names.
The class you have is not quite right unless you only want name and id and not the rest of the information. But using a Dictionary you wont need it anyway. The "trick" is to skip over the first part since you do not know the name. I can think of 2 ways to do this, but there are probably more/better ways.
Since json uses string keys pretty heavily, create a Dictionary, then get the data from it for the actual item:
jstr = ... from whereever
' create a dictionary
Dim jResp = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jstr)
' get the first/only value item
Dim jobj = jResp.Values(0) ' only 1 item
' if you end up needing the name/key:
'Dim key As String = jResp.Keys(0)
' deserialize first item to dictionary
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jobj.ToString)
' view results
For Each kvp As KeyValuePair(Of String, Object) In myItem
Console.WriteLine("k: {0} v: {1}", kvp.Key, kvp.Value.ToString)
Next
Output:
k: id v: 273746
k: name v: Chuck Noland
k: profileIconId v: 662
k: summonerLevel v: 30
k: revisionDate v: 1434821021000
Using String, String may also work, but it would convert numerics to string (30 becomes "30") which is usually undesirable.
While poking around I found another way to get at the object data, but I am not sure if it is a good idea or not:
' parse to JObject
Dim js As JObject = JObject.Parse(jstr)
' 1 = first item; 2+ will be individual props
Dim jT As JToken = js.Descendants(1)
' parse the token to String/Object pairs
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jT.ToString)
Same results.

Split query string in VB.net doesn't find the delimiter

I am passing a query string between asp.net pages in a VB.net application. I recieve the string by doing the following:
Dim pagename_username As String = Request.QueryString("field1")
The query string made up of a URL and a user_id, and is sent via JavaScript.
The string is then split in the VB page, by doing the following:
Dim parts As String() = pagename_username.Split(New String() {"|"}, StringSplitOptions.None)
Dim pagename As String = parts(0)
Dim username As String = parts(1)
This works fine for the following query string:
field1=http://**********/default.aspx|1
But gives an outside the bounds of the array error for the following query string:
field1=http://**********/docstore/browse.aspx?docstoreid=0&docstoretypeid=2|1
My suspicion is that the second string is too long??
If so, how can I solve it?
If not, what is the problem?
In a query string, you separate the parameters by the '&' sign. For example, the following query string has two parameters:
www.someurl.com?param1=1&param2=2
In your case:
field1=http://**********/docstore/browse.aspx?docstoreid=0&docstoretypeid=2|1
Notice the delimiter (i.e. '|') is in the second query string parameter, which is docstoretypeid, and not included in the value of field1. Therefore, when you call Request.QueryString("field1"), you aren't getting the full string that contains the pipe delimiter. That's why, your split fails and you are getting the exception.

Picking specific parts out of a query string

I have a query string which has more than one value being passed through it and I need to access the second passed value... I have this as of now:
If Request.QueryString("ANBOS") IsNot Nothing Then
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim index As Integer = url.IndexOf("-")
If index > 0 Then
url = url.Substring(0, index)
End If
DBTable = MaterialStuff.GetComponentsForMaterial(CInt(Request.QueryString(url)))
I'm attempting here to dumb everything after the first value I need, then go back and look at the query string where it's equal to ANBOS and get its value, but when I go get the value of it, the whole query string is still there, both values...
How do I make it so I just get the first value? Any help is greatly appreciated :)
Edit: Query String being passed through
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "MaterialNumberToUpdate=" & NextMaterialID)
Your query string is being generated incorrectly
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "MaterialNumberToUpdate=" & NextMaterialID)
should be..
Response.Redirect("Edit.aspx?ANBOS=" & CType(flxSearchResults.SelectedItem.Cells(1).Text, Integer) & "&MaterialNumberToUpdate=" & NextMaterialID)
This is because the query string uses ampersand signs (&) to separate key value pairs.

Getting the Request Variables from an ASP.NET page

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.

Resources