How to extract website hostname from full url using VB.NET? - asp.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

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.

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

asp .net query string encoding and decoding

I type the following url into my web browser and press enter.
http://localhost/website.aspx?paymentID=6++7d6CZRKY%3D&language=English
Now in my code when I do HttpContext.Current.Request.QueryString["paymentID"],
I get 6 7d6CZRKY=
but when I do HttpContext.Current.Request.QueryString.ToString() I see the following:
paymentID=6++7d6CZRKY%3D&language=English
The thing I want to extract the actual payment id that the user typed in the web browser URL. I am not worried as to whether the url is encoded or not. Because I know there is a weird thing going on here %3D and + sign at the same time ! But I do need the actual + sign. Somehow it gets decoded to space when I do HttpContext.Current.Request.QueryString["paymentID"].
I just want to extract the actual payment ID that the user typed. What's the best way to do it?
Thank you.
You'll need to encode the URL first, using URLEncode(). + in URL equals a space so needs to be encoded to %2b.
string paymentId = Server.UrlEncode("6++7d6CZRKY=");
// paymentId = 6%2b%2b7d6CZRKY%3d
And now
string result = Request.QueryString["paymentId"].ToString();
//result = 6++7d6CZRKY=
However
string paymentId = Server.UrlEncode("6 7d6CZRKY=");
//paymentId looks like you want it, but the + is a space -- 6++7d6CZRKY%3d
string result = Request.QueryString["paymentId"].ToString();
//result = 6 7d6CZRKY=
There is some info on this here: Plus sign in query string.
But I suppose you could also use a regular expression to get your parameter out of the query string. Something like this:
string queryString = HttpContext.Current.Request.QueryString.ToString();
string paramPaymentID = Regex.Match(queryString, "paymentID=([^&]+)").Groups[1].Value;
I sent an Arabic text in my query string
and when I resieved this string it was Encoded
after Server.UrlDecode
departmentName = Server.UrlDecode(departmentName);
it back again to arabic
I hope this help you

Looks like a query string, but won't act as a query string

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);
}

Modify request querystring parameters to build a new link without resorting to string manipulation

I want to dynamically populate a link with the URI of the current request, but set one specific query string parameter. All other querystring paramaters (if there are any) should be left untouched. And I don't know in advance what they might be.
Eg, imagine I want to build a link back to the current page, but with the querystring parameter "valueOfInterest" always set to be "wibble" (I'm doing this from the code-behind of an aspx page, .Net 3.5 in C# FWIW).
Eg, a request for either of these two:
/somepage.aspx
/somepage.aspx?valueOfInterest=sausages
would become:
/somepage.aspx?valueOfInterest=wibble
And most importantly (perhaps) a request for:
/somepage.aspx?boring=something
/somepage.aspx?boring=something&valueOfInterest=sausages
would preserve the boring params to become:
/somepage.aspx?boring=something&valueOfInterest=wibble
Caveats: I'd like to avoid string manipulation if there's something more elegant in asp.net that is more robust. However if there isn't something more elegant, so be it.
I've done (a little) homework:
I found a blog post which suggested copying the request into a local HttpRequest object, but that still has a read-only collection for the querystring params. I've also had a look at using a URI object, but that doesn't seem to have a querystring
This will work as long as [1] you have a valid URL to begin with (which seems reasonable) [2] you make sure that your new value ('sausages') is properly escaped. There's no parsing, the only string manipulation is to concatenate the parameters.
Edit
Here's the C#:
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
/* A NameValueColllection automatically makes room if this is a new
name. You don't have to check for NULL.
*/
nv["valueOfInterest"] = "sausages";
/* Appending to u.Query doesn't quite work, it
overloaded to add an extra '?' each time. Have to
use StringBuilder instead.
*/
StringBuilder newQuery = new StringBuilder();
foreach (string k in nv.Keys)
newQuery.AppendFormat("&{0}={1}", k, nv[k]);
u.Query = newQuery.ToString();
Response.Redirect(u.Uri.ToString());
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
nv["valueofinterest"] = "wibble";
string newQuery = "";
foreach (string k in nv.Keys)
{
newQuery += k + "=" + nv[k] + "&";
}
u.Query = newQuery.Substring(0,newQuery.Length-1);
Response.Redirect(u.ToString());
that should do it
If you can't find something that exists to do it, then build a bullet-proof function to do it that is thoroughly tested and can be relied upon. If this uses string manipulation, but is efficient and fully tested, then in reality it will be little different to what you may find any way.

Resources