Looks like a query string, but won't act as a query string - asp.net

I am working with VB in asp.net,
The basic problem is, I want to pair up the elements in a string, exactly like request.QueryString() will do to the elements in the query string of the web page.
However instead of the function looking at the current webpage query string I want it to look at a string (that is in the exact form of a query string) stored as a variable.
So if I define a string such as:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
I want a function that if I input LooksLikeAQueryString and "category1" it outputs "answer1" etc.
Is there anything that can already do this or do I have to build my own function? If I have to build my own, any tips?
I should add that in this case I won't be able to append the string to the url and then run request.QueryString.

You can use the HttpUtility.ParseQueryString method - MSDN link

ParseQueryString will do it for you - something along these lines:
Private Function QueryStringValue(queryString As String, key As String) As String
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(queryString)
For Each s As String In qscoll.AllKeys
If s = key Then Return qscoll(s)
Next
Return Nothing
End Function
Usage:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
Response.Write(QueryStringValue(LooksLikeAQueryString, "category2"))

If you dont want the dependancy of System.Web, of the top of my head
public string GetValue(string fakeQueryString,string key)
{
return fakeQueryString.Replace("?",String.Empty).Split('&')
.FirstOrDefault(item=>item.Split('=')[0] == key);
}

Related

Trying to search Active Directory using Ambiguous Name Resolution but it never returns anything

Unable to get it to return any results. Compiles fine and does not error when it is run, but the results are always empty.
I have got this working if I restrict it to something like DisplayName or given name. But would like it to work no matter if the user puts in forename or surname first and that the user is not restricted to adhering to the DisplayName format of "Surname, Forename"
Dim searchterm As String = RouteData.Values("Search")
Dim domain As New PrincipalContext(ContextType.Domain, "Domain")
Dim user As New CustomUserPrincipal(domain)
Dim search As New PrincipalSearcher()
Dim results As PrincipalSearchResult(Of Principal)
jss.MaxJsonLength = Integer.MaxValue
user.Anr = String.Format("*{0}*", searchterm)
search.QueryFilter = user
CType(search.GetUnderlyingSearcher, DirectoryServices.DirectorySearcher).SizeLimit = 25
results = search.FindAll()
<DirectoryObjectClass("user")>
<DirectoryRdnPrefix("CN")>
Public Class CustomUserPrincipal
Inherits UserPrincipal
Public Sub New(context As PrincipalContext)
MyBase.New(context)
End Sub
<DirectoryProperty("anr")>
Public Property Anr As String
Get
Return CStr(ExtensionGet("anr")(0))
End Get
Set(value As String)
ExtensionSet("anr", value)
End Set
End Property
End Class
I am expecting an object that I can enumerate through and pull out individual UserPrincipals to extract details. But I only get an empty object
I think this is your problem:
user.Anr = String.Format("*{0}*", searchterm)
Specifically, that you're putting asterisks around your search term. According to the documentation, it will expand a search term like (anr=Smith) to something like this:
(|(displayName=smith*)(givenName=smith*)(legacyExchangeDN=smith)(physicalDeliveryOfficeName=smith*)(proxyAddresses=smith*)(Name=smith*)(sAMAccountName=smith*)(sn=smith*))
Notice that it already does a "starts with" type search. Putting your own wildcards in there messes it up.
More specifically, it's the asterisk at the beginning. I tested this in our own AD environment. If I search for (anr=*Gabriel*) or (anr=*Gabriel), I get no results. If I search for (anr=Gabriel*) I get results, but it really has no effect on the results (the results are the same as if I had searched for (anr=Gabriel)).
The solution is to change that line to this:
user.Anr = searchterm
It is not exactly equivalent to the "contains" search you seem to want, but putting a wildcard at the beginning of any search really kills performance anyway. It can no longer use any indexes to complete the search, so it's forced to look at every user account in your domain.

How to get string from formatted url in asp.net c#

Suppose We are on the page www.abc.com/apple-store
then how to get string apple-store in asp C# code.
to store into another variable.
You can use string.last() to extract it.
string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();
You should use the Request.RawUrl property. See more details here.
Alternatelly you can also use the Request.Url (see here) property to get different parts of the current URL. For example you will get the same result using Request.Url.LocalPath.
You can get the url in a string variable. Further you can implement the below logic which will save the value in a variable.
string str = "www.abc.com/apple-store";
string result = "";
int i= 0;
int len = str.Length;
//Get the index of the character
i = str.IndexOf('/');
//store the result in the variable
result = str.Substring(i+1,len-i-1);
Console.WriteLine("Resultant:- {0}", result);`
Hope this helps a bit.

change query string values without redirect in c#

I have a query string that looks something like this:
"somename1=123&QueryString=PlaceHolder%3dNothing%26anotherid%3dsomevalue&somename=somevalue"
but I want the query string to be something like the query string below and replace the whole query string with the updated one is there any way to do that without redirection?
"somename1=somevalue1&PlaceHolder=Nothing&somename2=somevalue2&somename3=somevalue3"
basically need to remove:
"QueryString=" with empty string
"%3d" with "&"
"%26" with "="
So far I've done is:
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
strQueryString = strQueryString.Replace("QueryString=", "");
if (strQueryString.Contains("%26")) strQueryString = strQueryString.Replace("%26", "&");
if (strQueryString.Contains("%3d")) strQueryString = strQueryString.Replace("%3d", "=");
string x = strQueryString;
}
and:
// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
if (this.Request.QueryString.ToString().Contains("QueryString="))
{
this.Request.QueryString.ToString().Replace("QueryString=", "");
if (this.Request.QueryString.ToString().Contains("%26")) this.Request.QueryString.ToString().Replace("%26", "&");
if (this.Request.QueryString.ToString().Contains("%3d")) this.Request.QueryString.ToString().Replace("%3d", "=");
string x = this.Request.QueryString.ToString();
}
// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
The second part of the code is not replacing the characters and I don't know how after removing all character or replacing them change the query string to new query string.
Any help is greatly appreciated.
Changing the query string of the current request is not supported. Using private Reflection to edit some in-memory state will most likely break ASP.NET because it assumes that the query string is immutable. The only way to change the query string is to issue a new request, either by doing a redirect, or by doing a sort of sub-request, such as by making a new HTTP request to the same page but with a different query string.
May I suggest a not very well known built in key/value dictionary, Context.Items.
With this you very like get a better performance than toggle the readonly QueryString object, and it also last throughout a request so you can share it between module, handlers, etc.
Create
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
HttpContext.Current.Items("qs") = strQueryString.Replace("QueryString=", "").Replace("%26", "&").Replace("%3d", "=");
}
Use
string x = HttpContext.Current.Items("qs_d").ToString();
Side note: I shortened you code some, as there is no need to first check if anything contains and if so, replace, just run replace, it will be faster

NameValueCollection for editing query strings

If I call
var nvc = HttpUtility.ParseQueryString("?foo=bar&baz=robots")
I get back a NameValueCollection where if I call ToString on it, I get back a query string.
var str = nvc.ToString(); //foo=bar&baz=robots....
If I create a new NameValueCollection, add stuff to it, and call ToString() on it, I don't get back a query string.
var nvc= new NameValueCollection();
nvc["foo"] = "bar";
var str = nvc.ToString(); //default for Object.ToString()
Also there doesn't seem to be a way to construct a NameValueCollection that acts as a query string editor. Is there one? If not, why? Being able to edit query strings is a pretty useful thing, but this functionality is totally hidden away in an obscure mode of some object most people don't even know exists.
This is done by the internal HttpValueCollection class, which inherits NameValueCollection and overrides ToString().
ParseQueryString() is the only public way to construct this class.
In the end, query strings are meant to be very simple. So, you can just do something like this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("somekey", "someval");
var querystring = string.Join("&", dict.Select(kv => HttpUtility.UrlEncode(kv.Key) + "=" + HttpUtility.UrlEncode(kv.Value)));
Completely untested of course. But yeah, a query string is name=value separated by ampersands. Is there something else you need to do?

How to extract website hostname from full url using VB.NET?

I get ReffererUrl from current User, if refferer is exists i need to extract hostname without .com/.co.uk .... etc. value from it. So if ReffererUrl is http://main.something.biz/sup.aspx?r=e3432r3 i want to get just "something".
Doesn't matter whether it is Regex or something else.
thanks...
Note: it is just for your specs only: you can extend it by adding more condition at the end of my code. but i'd say that it wont work when path is like "abc.ss33.video.somthing.co.us"
Uri u = new Uri("http://main.something.biz/sup.aspx?r=e3432r3");
string a = u.DnsSafeHost;
string[] arr1 = a.Split('.');
string somethinVar = String.Empty;
if (arr1.Length == 3)
somethinVar = arr1[1];
There is no built-in way to do this in the sense you describe, because neither IIS nor ASP.NET knows the difference between the host name and domain name.
You have to write some code to do that.
an example could be:
string hostName=ReffererUrl.split('.')[1];
This code works only if the ReffererUrl look like the one you have posted and you have to make sure the array that the split function return an array with a number of elements greater than 1
HttpContext.Current.Request.ServerVariables("HTTP_HOST")
Extract domain with subdomain if present:-
Public Function ExtractSubAndMainDomainFromURL(URL As String) As String
'
' cut-off any url encoded data
URL = URL.Split("?"c)(0)
'return array of segments between slashes
Dim URLparts() As String = URL.Split("/"c)
'find first segment with periods/full-stops
Dim Domain As String = Array.Find(URLparts, Function(x) (x.Contains(".")))
'check if nothing returned - if necessary
If IsNothing(Domain) Then Domain = String.Empty
Return Domain
End Function

Resources